emwendelin (owner)

Fork Of

gist: 177420 by sanbornm Simple script to check when...

Forks

Revisions

  • 464d93 emwendelin Mon Sep 21 22:27:07 -0700 2009
  • 92a006 emwendelin Mon Sep 21 21:17:08 -0700 2009
  • 022a6c emwendelin Sun Sep 20 21:55:22 -0700 2009
  • 575ae4 emwendelin Tue Sep 15 15:52:12 -0700 2009
  • a99d7d emwendelin Tue Sep 15 15:47:17 -0700 2009
  • 02753f sanbornm Tue Sep 15 13:15:52 -0700 2009
  • d8061b sanbornm Sat Aug 29 00:14:32 -0700 2009
  • d7a9d3 sanbornm Sat Aug 29 00:14:10 -0700 2009
gist: 187610 Download_button fork
public
Description:
Pythonic site monitor
Public Clone URL: git://gist.github.com/187610.git
Embed All Files: show embed
Python #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python
 
# sample usage: checksites.py eriwen.com nixtutor.com yoursite.org
 
import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
 
def email_alert(message, status):
    fromaddr = 'you@gmail.com'
    toaddrs = 'yourphone@txt.att.net'
    
    server = SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login('you', 'password')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()
 
def get_site_status(url):
    response = get_response(url)
    try:
        if getattr(response, 'status') == 200:
            return 'up'
    except AttributeError:
     pass
    return 'down'
        
def get_response(url):
    '''Return response object from URL'''
    try:
        conn = HTTPConnection(url)
        conn.request('HEAD', '/')
        return conn.getresponse()
    except socket.error:
     return None
    except:
        logging.error('Bad URL:', url)
        exit(1)
        
def get_headers(url):
    '''Gets all headers from URL request and returns'''
    response = get_response(url)
    try:
        return getattr(response, 'getheaders')()
    except AttributeError:
     return 'Headers unavailable'
 
def compare_site_status(prev_results):
    '''Report changed status based on previous results'''
    
    def is_status_changed(url):
     status = get_site_status(url)
     friendly_status = '%s is %s' % (url, status)
     print friendly_status
     if url in prev_results and prev_results[url] != status:
            logging.warning(status)
            # Email status messages
            email_alert(str(get_headers(url)), friendly_status)
        prev_results[url] = status
 
    return is_status_changed
 
def is_internet_reachable():
    '''Checks Google then Yahoo just in case one is down'''
    if get_site_status('www.google.com') == 'down' and get_site_status('www.yahoo.com') == 'down':
        return False
    return True
    
def load_old_results(file_path):
    '''Attempts to load most recent results'''
    pickledata = {}
    if os.path.isfile(file_path):
        picklefile = open(file_path, 'rb')
        pickledata = pickle.load(picklefile)
        picklefile.close()
    return pickledata
    
def store_results(file_path, data):
    '''Pickles results to compare on next run'''
    output = open(file_path, 'wb')
    pickle.dump(data, output)
    output.close()
    
def main(urls):
    # Setup logging to store time
    logging.basicConfig(level=logging.WARNING, filename='checksites.log',
            format='%(asctime)s %(levelname)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
    
    # Load previous data
    pickle_file = 'data.pkl'
    pickledata = load_old_results(pickle_file)
        
    # Check sites only if Internet is_available
    if is_internet_reachable():
     status_checker = compare_site_status(pickledata)
     map(status_checker, urls)
    else:
        logging.error('Either the world ended or we are not connected to the net.')
        
    # Store results in pickle file
    store_results(pickle_file, pickledata)
 
if __name__ == '__main__':
    # First arg is script name, skip it
    main(sys.argv[1:])