check_pid.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env bash
  2. # Author: Jon Schipp
  3. # Date: 04-15-2014
  4. ########
  5. # Examples:
  6. # 1.) Check if sshd has restarted since last check
  7. # $ ./check_pid.sh -f /var/run/sshd.pid
  8. # Nagios Exit Codes
  9. OK=0
  10. WARNING=1
  11. CRITICAL=2
  12. UNKNOWN=3
  13. usage()
  14. {
  15. cat <<EOF
  16. Check if a service has been restarted by comparing its PID to each previous run.
  17. Options:
  18. -f Specify PID filename as full path
  19. -o Temporary PID file storage directory (def: /tmp)
  20. Usage: $0 -f /var/run/sshd.pid -o /tmp/pids/
  21. EOF
  22. }
  23. if [ $# -lt 1 ];
  24. then
  25. usage
  26. exit 1
  27. fi
  28. # Define now to prevent expected number errors
  29. DIR=/tmp
  30. CHECK=0
  31. COUNT=0
  32. while getopts "hf:o:" OPTION
  33. do
  34. case $OPTION in
  35. h)
  36. usage
  37. ;;
  38. f)
  39. FILEPATH="$OPTARG"
  40. CHECK=1
  41. ;;
  42. o)
  43. DIR="$OPTARG"
  44. ;;
  45. \?)
  46. exit 1
  47. ;;
  48. esac
  49. done
  50. FILE=$(echo $FILEPATH | sed 's/^.*\///')
  51. if [ ! -f $FILEPATH ]; then
  52. echo "File doesn't exist or is not a regular file!"
  53. exit $UNKNOWN
  54. fi
  55. if [ $CHECK -eq 1 ]; then
  56. if [ ! -f $DIR/$FILE ]; then
  57. echo "First run for PID or can't access file in temporary storage location: $DIR/$FILE"
  58. cp -f $FILEPATH $DIR
  59. exit $UNKNOWN
  60. fi
  61. # In case the PID is temporarily locked by another program
  62. until [ ! -z $NEWPID ] && [ ! -z $OLDPID ];
  63. do
  64. NEWPID=$(cat $FILEPATH)
  65. OLDPID=$(cat $DIR/$FILE)
  66. COUNT=$((COUNT+1))
  67. if [ $COUNT -ge 10 ]
  68. then
  69. break
  70. fi
  71. done
  72. if [ $NEWPID -eq $OLDPID ]; then
  73. echo "Service is still running with the same PID: $(echo $NEWPID)"
  74. cp -f $FILEPATH $DIR
  75. exit $OK
  76. else
  77. echo "Service restarted. OLDPID: $(echo $OLDPID) NEWPID: $(echo $NEWPID)"
  78. cp -f $FILEPATH $DIR
  79. exit $CRITICAL
  80. fi
  81. fi