Quick and Dirty Website Monitoring (bash script)
Because of the nature of my work I deal with a lot of websites. Given the specifics of these projects, I sometimes need to keep an eye on web resource availability for a while after a project is finished.
It occurred to me to simplify this. I didn’t want to bother with Nagios or Zabbix for such a simple task. What I ended up with is this script, which runs on my machine:
#/bin/bash
html=/var/www/servers_state.html
while true; do
echo "<br><br><br>" > $html
echo '<center><table width="40%" border="1" cellspacing="0" cellpadding="5" >' >> $html
echo "<tr><td></td><td><b>HOST</b></td><td><b>State</b></td></tr>" >> $html
i=1
serverlist=(website1.com website2.com website3.com website4.com website4.com)
for web in "${serverlist[@]}";do
state=$(HEAD -t 8 $web |sed -n 1p)
echo "<tr><td>$i</td><td>$ip</td><td>$state</td></tr>" >> $html
if [ "$state" != "200 OK" ]
then
echo "Something is wrong with $ip" |mail -s "Invalid responce from $web" \ [email protected]
fi
let "i = $i +1"
done
echo "</table>" >> $html
echo "<br>" >> $html
echo "<p>Last updated at $(date +%H:%M:%S)</p>" >> $html
echo "</center>" >> $html
sleep 30
done
The serverlist variable holds the list of sites to check.
Every 30 seconds the script sends a HEAD request to each site in serverlist and checks the response code. All this info gets written to servers_state.html. If the response code isn’t 200 - the script sends me an email notification.
As a result I have a little table with the state of the sites as of the previous script run, at
http://localhost/servers_state.html
And in my inbox I get info about resource downtime accurate to within 30 seconds.
Actually I simplified the notification scheme a bit here. In practice you can send notifications somewhere other than email, say to Skype.