Wednesday, June 06, 2012

Simple HTTP monitor on CentOS / RH

This is just a small memo note on how to do an HTTP monitoring script. Be aware, there are tons of other ways to do it, this one is simple but might not be the best for you.

1. In your home folder, create httpmonitor.sh script file, replace the e-mail address with the one you want your notifications to go to:

#!/bin/bash
# Simple HTTP monitor script
# Monitors a URL and sends an email when the status of it changes
NOTIFY_EMAIL=MY_EMAIL_ADDRESS@MYDOMAIN.com
if [ -z $1 ]; then
  echo Usage: $0 url_to_monitor
  echo Example: $0 http://www.google.com/
 exit 1
fi

  URL=$1
  STATUS_FILE_PREFIX=.`echo $URL | sed -s 's/[\/\.:]/-/g'`
  RESULT_TEXT=`lwp-request -m HEAD -t 30 $URL | head -n 1`
  STATUS_FILE_SUFFIX=`echo $RESULT_TEXT | sed -s 's/ /-/g'`

  if [ ! -f $STATUS_FILE_PREFIX.$STATUS_FILE_SUFFIX ]; then
    rm "$STATUS_FILE_PREFIX".* > /dev/null 2>&1
    touch $STATUS_FILE_PREFIX.$STATUS_FILE_SUFFIX
    echo $URL returned $RESULT_TEXT | mail -s "[$0]: $URL returned $RESULT_TEXT"
 $NOTIFY_EMAIL
  fi

exit $RESULT

2. chmod a+x httpmonitor.sh so that cron job can execute it

3. run ./httpmonitor.sh <theurl> manually to check script executes with no errors

4. crontab -e (most probably it will be vi, so do 'i' to insert a line and, e.g. to check every 10 minutes:)
10 * * * * /home/MYUSERNAME/httpmonitor.sh http://myurl.com

hit ESC and type ':wq!'

5. check with crontab -l that the line looks like you want it

That's it. It will send you e-mails whenever HTTP status of the URL changes (say, from 200 to 503 or if it will time out)

Attributions:
The script is taken from Confessions of the Guru blog with a fix for rm quotes and using full lwp-request instead of just HEAD. 

No comments: