Pages

Showing posts with label curl. Show all posts
Showing posts with label curl. Show all posts

Friday, August 20, 2010

Simple script to alert you when websites are down

Suppose your clients and boss would like to know when a site you maintain should go down.

You can write your own script to achieve this goal, where you implement a light-weight http client in python-twisted... but why bother?

There is a thing called reinventing the wheel.


So what do we need?
  1. curl;
  2. logrotate;
  3. mutt;
  4. A list of urls;
  5. A log file to record visits by curl;
  6. A script called site-checker, which one puts in the /etc/cron.hourly/ and chmod 770 /etc/cron.hourly/site-checker:


    #!/bin/bash
    
    #set -e -x
    
    FILELOC=/home/user/bin/websites.list
    LOGFILE=/home/user/bin/log/site-checker.log
    WEBSITES=$(cat $FILELOC | xargs)
    UDATE=$(date -u)
    EMAILADDR=user@nowhere.com
    for w in $WEBSITES
    do
      echo "==Fetched $w on $UDATE==" >> $LOGFILE
      curl -sf $w || echo "Warning: $w is down on $UDATE" | mutt -s "[website down] $UDATE $w" $EMAILADDR $
    done
    

websites.list would contain something like this:

www.microsoft.com
www.google.com
www.sap.com
www.oracle.com

For mutt to send e-mails you either need to setup a MTA (mail-transfer agent) or add a .muttrc file to your $HOME, containing something like this:

set smtp_url="smtp://user@smtp.woohoo.com"
set smtp_pass="tuff2guess"

You also have to prevent your site-checker.log from growing too big with logrotate.

Type this in your bash shell:

echo -e "/home/user/bin/log/*.log {\n\
  daily\n\
  missingok\n\
  size=100k\n\
  rotate 5\n\
}" > /etc/logrotate.d/user-custom\


As with every single script on this blog, you must adapt the script to your own needs.

Happy hacking!


Update 21-dec-2010:
#!/bin/bash
FILELOC=/home/user/bin/websites.list
PEOPLELOC=/home/user/bin/people.list
LOGFILE=/home/user/bin/site-checker.log
WEBSITES=$(cat $FILELOC | xargs)
UDATE=$(date -u)

mail () {
  read message
  domainname=$1
  for addr in $(cat $PEOPLELOC | xargs)
  do
    echo $message | mutt $addr -s "[website down] $UDATE $domainname" 2> /dev/null
  done
}

for w in $WEBSITES
do
  touch $LOGFILE
  echo "==Fetched $w on $UDATE==" >> $LOGFILE
  curl -sf $w || echo "Warning: $w is down on $UDATE" | mail $w
done