diff options
Diffstat (limited to 'lib/nagios')
-rwxr-xr-x | lib/nagios/nagios.sh | 125 |
1 files changed, 125 insertions, 0 deletions
diff --git a/lib/nagios/nagios.sh b/lib/nagios/nagios.sh new file mode 100755 index 0000000..40631c1 --- /dev/null +++ b/lib/nagios/nagios.sh @@ -0,0 +1,125 @@ +cd $(dirname "$0") + +. setup/parameters.sh + +function nagios_find_host { + echo "$@" | grep -oP '\-H\s*\K[^\s]*' +} + +function find_host_param { + local id="$1" && shift + local pname="$1" && shift + local defval="$1" && shift + + local val=$(cat setup/${pname}.txt | grep -P "^$id" | awk '{ print $2 }') + [ -n "$val" ] || val="$defval" + + echo -n "$val" +} + +function nagios_find_host_param { + local pname="$1" && shift + local defval="$1" && shift + local host=$(nagios_find_host "$@") + + find_host_param "$host" "$pname" "$defval" +} + +function resolve_fqdn { + local host="$1" && shift + + if [[ ! $host =~ \. ]]; then + local domain=$(find_host_param "$host" domains "$default_domain") + host+=".$domain" + fi + + echo -n $host +} + +function resolve_ip { + local host="$1" && shift + + if [[ ! "$host" =~ ^[[:digit:]] ]]; then + local fqdn=$(resolve_fqdn "$host") + host=$(dig +short "$fqdn" A | head -n 1 | tr -d '\n') + if [ $? -ne 0 -o -z "$host" ]; then + echo "DNS resolution for host ($fqdn) failed: $(dig +short "$fqdn" A 2>&1)" + exit 2 + fi + fi + + echo -n "$host" +} + +function nagios_run { + if [[ "$1" =~ ^- ]]; then + cmd=${nagios_plugins}/$(basename $0) + else + cmd=$1 && shift + [[ "$cmd" =~ ^/ ]] || cmd="${nagios_plugins}/$cmd" + fi + + ARGS="" + while [[ $# -gt 0 ]]; do + key="$1" && shift + + case "$key" in + -H) + host="$1" && shift + ip=$(resolve_ip "$host") + if [ $? -eq 0 -a -n "$ip" ]; then + ARGS+=" ${key} $ip" + else + echo "$ip" + exit $? + fi + ;; + *) + ARGS+=" $key" + esac + done + + [ -n "$debug" ] && echo "$(date) $cmd" "$ARGS" >> /tmp/nagios.log + eval "$cmd" "$ARGS" +} + +function nagios_parse { + cmd="$1"; shift + + output=$($cmd "$@") + exit_code=$? + + if [ $exit_code -eq 0 ]; then + last_line=$(echo "$output" | tail -1) + + status=$(echo $last_line | cut -d ' ' -f 1) + [[ "$status" =~ ^[0-9]$ ]] || status=0 + echo -n ${last_line#$status} + else + status=0 + fi + + if [ $status -ne 1 ]; then + echo -n " -- " + + lines=$(echo "$output" | sed '/^[[:space:]]*$/d' | wc -l) + if [ $lines -gt 1 ]; then + echo "$output" | sed '/^[[:space:]]*$/d' | head -n 1 | tr -d '\n' + echo " ... " + echo "------------------" + echo "$output" | head -n -1 + else + echo "$output" | sed '/^[[:space:]]*$/d' | head -n -1 + fi + else + echo + fi + + if [ "$status" -eq 0 ]; then + exit "2" + elif [ "$status" -eq 1 ]; then + exit "0" + else + exit "1" + fi +} |