#!/usr/bin/env python
#
# script to monitor if website is up and send email if not
#
# crontab test entry: 15 * * * * /usr/bin/python /home/sites/example.com/scripts/sitemon.py >/dev/null 2>/home/sites/example.com/logs/cron.log
# means ping site every 15 minutes
#
# techtonik // php.net 2008-03-30

#SITE = 'http://example.com'
SITE = "http://www.dummy-site.com/test_timeout.html"
TIMEOUT = 30
MAILSERV = "smtp.gmail.com"
#MAILSERV = None
#Use secure TLS connections - required by GMail
SECURE = 1
SMTPDEBUG = 0

LOGIN="example@gmail.com" #: Unset login to skip authentication
PASS=None  #: If pass is None it will be asked

FROM = "example@gmail.com"
TO = "example@gmail.com"
CC = "example@php.net"



from string import Template
from time import ctime
from getpass import getpass

MSGTPL = Template("""\
From: $sndr\r\n\
To: $rcpt\r\n\
Cc: $cc\r\n\
Reply-To: $cc\r\n\
Subject: Site is down - $site\r\n\
\r\n\
Request to $site experienced timeout.\r\n\
\r\n\
Event time: $ctime\r\n\
Timeout   : $timeout sec\r\n\
\r\n\
\r\n\
-- \r\n\
site monitoring script from rainforce.org\r\n\
""")
MSG = MSGTPL.substitute(sndr=FROM, rcpt=TO, cc=CC, site=SITE, ctime=ctime(), timeout=TIMEOUT)


import socket
import urllib2

def timeout(site, timeout):
  save = socket.getdefaulttimeout() 
  socket.setdefaulttimeout(timeout)
  try:
    response = urllib2.urlopen(site)
  except urllib2.URLError, err:
    if err.__class__.__name__ == "URLError":
      if isinstance(err[0], socket.timeout):
        socket.setdefaulttimeout(save)
        return True
  socket.setdefaulttimeout(save)
  return False


def email_warning(sndr, rcpt, site):
  try:
    # starting from Python 2.5
    from email.mime.text import MIMEText
  except ImportError:
    from email.MIMEText import MIMEText
  import smtplib

  # Be warned that even though To: and Cc: headers are present in the message, SMTP
  # protocol still requires that all recepient addresses are passed to server explicitly

  server = smtplib.SMTP()
  if SMTPDEBUG:
    server.set_debuglevel(1)
  server.connect(MAILSERV)
  if SECURE:
    server.ehlo()
    server.starttls()
    server.ehlo()
  if LOGIN != None:
    if PASS == None:
      pswd = getpass()
    else:
      pswd = PASS
    server.login(LOGIN, pswd)
  server.sendmail(sndr, rcpt, MSG)
  server.quit()



if __name__ == "__main__":
  if timeout(SITE, TIMEOUT):
    print "Timeout detected"
    email_warning(FROM, (TO, CC), SITE)
  else:
    print "All OK"
    pass