aboutsummaryrefslogtreecommitdiff
path: root/nagios-acknowledge
blob: 5878e4065e19502b6d1207ec91b55777c09bc3d8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env bash

#
# nagios-acknowledge(1) -- Shortcut to acknowledge problems in Nagios, because
# it's annoying to do with the web interface for large sets of hosts or
# services.
#
#     $ nac <host>[/<service>] [optional comment]
#
# Good for for/while loops:
#
#   for hostname in hosta hostb hostc; do nac "$hostname" ... ; done
#   while read -r hostname; do nac "$hostname" ... ; done < downtime-hostnames
#
# By default, does not send ACKNOWLEDGEMENT notifications. Use -n if you do
# want that.
#
# Author: Tom Ryder <tom@sanctum.geek.nz>
# Copyright: 2014 Sanctum
#

# Name self
self=nagios-acknowledge

# Usage printing function
usage() {
    printf 'USAGE: %s [-n] <host[/service]> [comment]\n' "$self"
}

# Default to not notifying
notify=0

# Figure out whether we should notify
OPTIND=1
while getopts 'hn' opt ; do
    case "$opt" in
        n)
            notify=1
            ;;
        h)
            usage
            exit 0
            ;;
        '?')
            usage >&2
            exit 1
            ;;
    esac
done
shift "$((OPTIND-1))"

# Bail if no arguments left; we need at least the host/service name
if ! (($#)) ; then
    usage >&2
    exit 1
fi

# Define relatively fixed/guaranteed fields for Nagios command; note that the
# comment has a default of 'no comment given'
now=$(date +%s)
spec=$1
sticky=1
notify=$notify
persistent=1
author=${SUDO_USER:-$USER}
comment=${2:-'no comment given'}
cmdfile=${NAGCMD_FILE:-/usr/local/nagios/var/rw/nagios.cmd}

# If a service name is specified after a slash, figure that out
if [[ $spec == */* ]] ; then
    host=${spec%/*}
    service=${spec##*/}
else
    host=$spec
    service=
fi

# Quietly replace semicolons in comment with commas
comment=${comment//;/,}

# Write command and print message if it fails; succeed silently
if [[ $service ]] ; then
    cmd=$(printf '[%lu] ACKNOWLEDGE_SVC_PROBLEM;%s;%s;%u;%u;%u;%s;%s' \
        "$now" "$host" "$service" \
        "$sticky" "$notify" "$persistent" "$author" "$comment")
else
    cmd=$(printf '[%lu] ACKNOWLEDGE_HOST_PROBLEM;%s;%u;%u;%u;%s;%s' \
        "$now" "$host" \
        "$sticky" "$notify" "$persistent" "$author" "$comment")
fi

# Attempt to write command to file
if ! printf '%s\n' "$cmd" > "$cmdfile" ; then
    printf '%s: Failed to write command to file\n' "$self" >&2
    exit 1
fi