#!/usr/bin/env bash # # nagios-downtime(1) -- Shortcut to scheduling fixed downtime in Nagios, # because it's annoying to do with the web interface for large sets of hosts # or services. # # $ ndt [/] [optional comment] # # Good for for/while loops: # # for hostname in hosta hostb hostc; do ndt "$hostname" ... ; done # while read -r hostname; do ndt "$hostname" ... ; done < downtime-hosts # # Assumes date(1) with +%s format and --date option (probably only GNU date). # # Author: Tom Ryder # Copyright: 2014 Sanctum # # Name self self=nagios-downtime # Usage printing function usage() { printf 'USAGE: %s [comment]\n' "$self" } # Process options (just help at the moment) OPTIND=1 while getopts 'h' opt ; do case "$opt" in h) usage exit 0 ;; '?') usage >&2 exit 1 ;; esac done shift "$((OPTIND-1))" # Bail if too few arguments left; we need at least the hostname, the start date, and the end date if (($# < 3)) ; 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 fixed=1 trigger=0 duration=0 author=${SUDO_USER:-$USER} comment=${4:-'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//;/,} # Attempt to parse start and end dates; fail usefully if the call doesn't work if ! dtstart=$(date +%s --date "$2") ; then printf '%s: Could not parse start date %s' "$self" "$2" >&2 exit 1 fi if ! dtend=$(date +%s --date "$3") ; then printf '%s: Could not parse end date %s' "$self" "$3" >&2 exit 1 fi # Write command and print message if it fails; succeed silently if [[ $service ]] ; then cmd=$(printf '[%lu] SCHEDULE_SVC_DOWNTIME;%s;%s;%s;%s;%u;%u;%u;%s;%s' \ "$now" "$host" "$service" "$dtstart" "$dtend" \ "$fixed" "$trigger" "$duration" "$author" "$comment") else cmd=$(printf '[%lu] SCHEDULE_HOST_DOWNTIME;%s;%s;%s;%u;%u;%u;%s;%s' \ "$now" "$host" "$dtstart" "$dtend" \ "$fixed" "$trigger" "$duration" "$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