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:
- Save the above as monitor.sh in your favourite directory.
- Edit it and change the NOTIFY_EMAIL address to your own
- chmod u+x monitor.sh
- 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.
4 Comments
Other Links to this Post
RSS feed for comments on this post. TrackBack URI
By Frank, September 6, 2008 @ 6:23 am
Handy! How would you tie something like this in with an alert on your ubuntu desktop say? I’m new to bash scripting and I think that would be very cool.
By
Omer, July 15, 2011 @ 10:37 pm
Hello,
the script you created works perfectly for me. I am using it to monitor multiple website urls.
Great job! nice script!
Thanks
Omer
By
Joel Thompson, September 14, 2011 @ 4:54 pm
Hi, thanks for the script, we tried to use this script for our new external webserver but found it wasnt deleting the hidden files in the folder. This resulted in it not warning you when the site went up/down untill these hidden files were deleted.
The fix was to move the .* out of the double qoutes when checking for the hidden files to remove, like so.
rm “$STATUS_FILE_PREFIX”.* > /dev/null 2>&1
After that it has been working brilliantly, thanks.
By
GuruBob, October 25, 2011 @ 1:09 pm
Cheers Joel – I hadn’t spotted that