Advertisement
homer512

poll sites

May 20th, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3. """see http://www.craigaddyman.com/python-script-to-monitor-site-up-time/"""
  4.  
  5.  
  6. import sched
  7. import time
  8. import urllib2
  9.  
  10.  
  11. def notify_down(url, email):
  12.     print "Hey %s, %s is down" % (email, url)
  13.  
  14.  
  15. def notify_up(url, email):
  16.     print "Hey %s, %s is up again" % (email, url)
  17.  
  18.  
  19. POLL_TIME_UP = 60 # 1 min
  20. POLL_TIME_DOWN = 60 * 15 # 15 min
  21.  
  22.  
  23. def poll(scheduler, url, email, lastup = True):
  24.     """Checks the given URL, notifies on status changes and schedules again
  25.  
  26.    Arguments:
  27.    scheduler -- sched.scheduler. Function will schedule itself again with
  28.                 POLL_TIME_UP or POLL_TIME_DOWN
  29.    url -- http or https URL. GET request will be made. Response code 200 is
  30.           expected
  31.    email -- e-mail address that will be notified when site changes from up to
  32.             down or vice versa
  33.    lastup -- True if the site was up on the last check
  34.    """
  35.     print "Checking %s" % url
  36.     try:
  37.         response = urllib2.urlopen(url)
  38.         try:
  39.             isup = response.getcode() == 200
  40.         finally:
  41.             response.close()
  42.     except (urllib2.URLError, urllib2.HTTPError):
  43.         isup = False
  44.     if isup:
  45.         if not lastup:
  46.             notify_up(url, email)
  47.         polltime = POLL_TIME_UP
  48.     else:
  49.         if lastup:
  50.             notify_down(url, email)
  51.         polltime = POLL_TIME_DOWN
  52.     # schedule self for next iteration
  53.     scheduler.enter(polltime, 0, poll, (scheduler, url, email, isup))
  54.  
  55.  
  56. def main():
  57.     scheduler = sched.scheduler(time.time, time.sleep)
  58.     observed = (('http://www.example.com', 'john.doe@example.com'),
  59.                 ('http://localhost', 'root@localhost'),
  60.             )
  61.     for url, email in observed:
  62.         # check immediately, then adds itself to scheduler
  63.         poll(scheduler, url, email)
  64.     scheduler.run()
  65.  
  66.  
  67. if __name__ == '__main__':
  68.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement