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 script file, replace the e-mail address with the one you want your notifications to go to:

# Simple HTTP monitor script
# Monitors a URL and sends an email when the status of it changes
if [ -z $1 ]; then
  echo Usage: $0 url_to_monitor
  echo Example: $0
 exit 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'`

    rm "$STATUS_FILE_PREFIX".* > /dev/null 2>&1
    echo $URL returned $RESULT_TEXT | mail -s "[$0]: $URL returned $RESULT_TEXT"

exit $RESULT

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

3. run ./ <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/

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)

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: