Monday, April 4, 2016

Bash script to notify me when a web site is up

One of the systems we depend on is down, and I wanted to get notified when it gets back up. And because I am lazy (Isn't that the motive for everything?) I wanted to write a script that checks it for me and mail me when the system gets back up.

Here is the script content:

curl -s -o "/dev/null" $1
if [ $? -eq 0 ] ; then
        if [ ! -f /data/epricer/utils/notified.status ] ; then
                echo "$1 is now up!" | mail -s "Website is up" $2
                touch /data/epricer/utils/notified.status
        fi

fi

This script takes two params, the first is the URL to check, and the 2nd is the email to notify. The scripts also creates a file when the server gets up, then check for it again when sending the notification, to prevent it from spamming my mail with thousands of "It is up" mails. I only need the notification once.

Save that in a file let's call /data/utils/notifyMe.sh. And make it executable. 

Then setup crontab to run this file periodically (for me it is every 10 mins) by issuing 

crontab -e

and adding the text below to a new line of the file 

10,20,30,40,50,59 * * * * /data/utils/notifyMe.sh https://mysystem.com myemail@domain.com

Save crontab and viola, you will be notified when the system is up. This took around 5 mins, but it is handy.