HTTP Monitor Script for Bash

If you run a web application, or want to know when a web server goes up or down. There’s a range of products you can use to do this, such as Nagios (URL monitoring is only one aspect of server monitoring that Nagios can perform). There are times however when configuring a full blown monitoring system like Nagios is way over the scope of what you want to do right now.

Here’s a script I use to monitor URL’s. I put this in my cron to run every 5 minutes. It only emails you when the HTTP status of the URL has changed since last time you requested it. This should avoid heaps of emails in your inbox, unless you have a bouncy server.

#!/bin/bash
# Simple HTTP monitor script
# Monitors a URL and sends an email when the status of it changes

NOTIFY_EMAIL=youremailhere@yourdomainname.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=`HEAD $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

This should work on a stock Ubuntu/Debian system. To actually use this script:

  1. Save the above as monitor.sh in your favourite directory.
  2. Edit it and change the NOTIFY_EMAIL address to your own
  3. chmod u+x monitor.sh
  4. Invoke it like this: ./monitor.sh http://www.google.com/

What you do with it is up to you. Note that to track the status this script will create hidden files in the current directory. For example, if Google returns a 200 OK status, a hidden file called .http—www-google-com-.200-OK will be created.

WordPress Themes