homer512 icon

poll sites

homer512 | PRO | 05/20/14 05:10:23 PM UTC | 0 ⭐ | 745 👁️ | Never ⏰ | []
Python |

1.87 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/python2
 
"""see http://www.craigaddyman.com/python-script-to-monitor-site-up-time/"""
 
 
import sched
import time
import urllib2
 
 
def notify_down(url, email):
    print "Hey %s, %s is down" % (email, url)
 
 
def notify_up(url, email):
    print "Hey %s, %s is up again" % (email, url)
 
 
POLL_TIME_UP = 60 # 1 min
POLL_TIME_DOWN = 60 * 15 # 15 min
 
 
def poll(scheduler, url, email, lastup = True):
    """Checks the given URL, notifies on status changes and schedules again
 
    Arguments:
    scheduler -- sched.scheduler. Function will schedule itself again with
                 POLL_TIME_UP or POLL_TIME_DOWN
    url -- http or https URL. GET request will be made. Response code 200 is
           expected
    email -- e-mail address that will be notified when site changes from up to
             down or vice versa
    lastup -- True if the site was up on the last check
    """
    print "Checking %s" % url
    try:
        response = urllib2.urlopen(url)
        try:
            isup = response.getcode() == 200
        finally:
            response.close()
    except (urllib2.URLError, urllib2.HTTPError):
        isup = False
    if isup:
        if not lastup:
            notify_up(url, email)
        polltime = POLL_TIME_UP
    else:
        if lastup:
            notify_down(url, email)
        polltime = POLL_TIME_DOWN
    # schedule self for next iteration
    scheduler.enter(polltime, 0, poll, (scheduler, url, email, isup))
 
 
def main():
    scheduler = sched.scheduler(time.time, time.sleep)
    observed = (('http://www.example.com', '[email protected]'),
                ('http://localhost', 'root@localhost'),
            )
    for url, email in observed:
        # check immediately, then adds itself to scheduler
        poll(scheduler, url, email)
    scheduler.run()
 
 
if __name__ == '__main__':
    main()

Comments