Jailout2000

Web Server Health Script (./healthcheck.sh)

Mar 20th, 2014
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.77 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. ##
  4. # Server Health Script
  5. # Executes Curl and checks the HTTP response code repeatedly. Sends an email if code is not 200 or 302.
  6. #
  7. # Example to check Google every 5 minutes silently, even after shell user logs out:
  8. # $ ./healthcheck.sh http://google.com Google 300 > /dev/null &
  9. ##
  10.  
  11. if [ "$1" = "" ]; then
  12.   echo -en "\nUsage: $0 <url> [title] [timer]\n\n"
  13.   echo -en "  url  - Required. The page to target\n"
  14.   echo -en "title  - Optional. The title of this check, used in emails;\n"
  15.   echo -en "         if left blank, title will assume the url\n"
  16.   echo -en "timer  - If set, sleep in [timer] seconds after a check,\n"
  17.   echo -en "         otherwise execute checks back-to-back\n\n"
  18.   echo -en "Exit codes:\n\n"
  19.   echo -en "0 - success or canceled script\n"
  20.   echo -en "1 - required parameters not provided\n\n"
  21.   echo -en "Author: Carl Bennett\n"
  22.   echo -en "License: CC-BY-SA 3.0\n\n"
  23.   exit 1
  24. else
  25.   URL=$1
  26. fi
  27.  
  28. if [ "$2" = "" ]; then
  29.   TITLE=$URL
  30. else
  31.   TITLE=$2
  32. fi
  33.  
  34. if [ "$3" = "" ]; then
  35.   SLEEP_TIMER=0
  36. else
  37.   SLEEP_TIMER=$3
  38. fi
  39.  
  40. EMAIL_ADDRESS_FROM="server-health"
  41. EMAIL_ADDRESS_TO="noc"
  42. EMAIL_SUBJECT="Failure status notification for $TITLE"
  43. EMAIL_MESSAGE="Failed to retrieve a 200 OK status while checking $TITLE."
  44.  
  45. i=0
  46. while true; do
  47.   ((i++))
  48.   echo -n "Check $i..."
  49.   FIRSTLINE=`curl -s -D- -o/dev/null $URL | head -n 1`
  50.   CODE=`echo -n "$FIRSTLINE" | awk '{print $2}'`
  51.   if [ "$CODE" != "200" ] && [ "$CODE" != "302" ]; then
  52.     echo "failed, sending email..."
  53.     echo -ne "To: $EMAIL_ADDRESS_TO\nFrom: $EMAIL_ADDRESS_FROM\nSubject: $EMAIL_SUBJECT\n\n$EMAIL_MESSAGE\n\nURL: $URL\nStatus: $FIRSTLINE" | sendmail $EMAIL_ADDRESS_TO
  54.   else
  55.     echo "success."
  56.   fi
  57.   if [ $SLEEP_TIMER -ge 1 ]; then
  58.     sleep $SLEEP_TIMER
  59.   fi
  60. done
Advertisement
Add Comment
Please, Sign In to add comment