negate.sh 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env bash
  2. # Author: Jon Schipp
  3. ########
  4. # Examples:
  5. # 1.) Check status code for uptime using the defaults
  6. # $ ./check_negate.sh -r /usr/bin/uptime
  7. #
  8. # 2.) Custom service does it backwards and exits 1 when running and 0 when stopped.
  9. # $ ./check_negate.sh -r "/usr/sbin/service custom-server status" -o 1 -c 0
  10. # Nagios Exit Codes
  11. NAGIOS_OK=0
  12. NAGIOS_WARNING=1
  13. NAGIOS_CRITICAL=2
  14. NAGIOS_UNKNOWN=3
  15. # Mutable Nagios Exit Codes
  16. OK=0
  17. WARNING=1
  18. CRITICAL=2
  19. UNKNOWN=3
  20. usage()
  21. {
  22. cat <<EOF
  23. Checks the status, or exit, code of another program and returns a
  24. Nagios status code based on the result.
  25. Options:
  26. -r <cmd> Absolute path of program to run, use quotes for options
  27. -o <int> Status to expect for OK state (def: 0)
  28. -w <int> Status to expect for WARNING state (def: 1)
  29. -c <int> Status to expect for CRITICAL state (def: 2)
  30. -u <int> Status to expect for UNKNOWN state (def: 3)
  31. Usage: $0 -r "/usr/sbin/service sshd status"
  32. EOF
  33. }
  34. argcheck() {
  35. # if less than n argument
  36. if [ $ARGC -lt $1 ]; then
  37. echo "Missing arguments! Use \`\`-h'' for help."
  38. exit 1
  39. fi
  40. }
  41. ARGC=$#
  42. argcheck 1
  43. while getopts "hc:o:r:w:u:" OPTION
  44. do
  45. case $OPTION in
  46. h)
  47. usage
  48. exit 0
  49. ;;
  50. r) if ! [ -z $RUN ]; then
  51. echo "Error: Argument \`\`-r'' is required''."
  52. exit 1
  53. else
  54. RUN="$OPTARG"
  55. fi
  56. ;;
  57. o)
  58. OK=$OPTARG
  59. ;;
  60. w)
  61. WARNING=$OPTARG
  62. ;;
  63. c)
  64. CRITICAL=$OPTARG
  65. ;;
  66. u)
  67. UNKNOWN=$OPTARG
  68. ;;
  69. \?)
  70. exit 1
  71. ;;
  72. esac
  73. done
  74. COMMAND=$(echo $RUN | sed 's/ .*//')
  75. if ! [ -x $COMMAND ]; then
  76. echo "Error: $COMMAND does not exist, is not an absolute path, or is not executable."
  77. exit 1
  78. fi
  79. $RUN
  80. CODE=$?
  81. if [ $CODE -eq $OK ]; then
  82. exit $NAGIOS_OK
  83. elif [ $CODE -eq $WARNING ]; then
  84. exit $NAGIOS_WARNING
  85. elif [ $CODE -eq $CRITICAL ]; then
  86. exit $CRITICAL
  87. elif [ $CODE -eq $UNKNOWN ]; then
  88. exit $NAGIOS_UNKNOWN
  89. else
  90. echo "Exit code not understood: $CODE"
  91. fi