|
#!/usr/bin/python |
|
|
|
""" |
|
A simple website HTTP header monitor tool. |
|
""" |
|
|
|
import re |
|
import urllib2 |
|
|
|
|
|
def monitor_url(url, tests): |
|
response = urllib2.urlopen(url) |
|
info = response.info() |
|
info['Status'] = str(response.getcode()) |
|
for header, pattern in tests: |
|
value = info.getheader(header) |
|
if not re.match(pattern, value): |
|
raise AssertionError( |
|
'%s: %s does not match %s' % |
|
(header, value, pattern)) |
|
|
|
if __name__ == '__main__': |
|
import config |
|
from os.path import exists |
|
from email.mime.text import MIMEText |
|
from subprocess import Popen, PIPE |
|
|
|
messages = [] |
|
for row in config.urls: |
|
try: |
|
if isinstance(row, basestring): |
|
url = row |
|
monitor_url(url, []) |
|
elif hasattr(row, '__getitem__') and hasattr(row, '__len__'): |
|
if len(row) > 1: |
|
url, tests = row[0], row[1] |
|
monitor_url(url, tests) |
|
except urllib2.URLError, e: |
|
# Ignore these messages |
|
pass |
|
except Exception, e: |
|
messages.append([url, str(e)]) |
|
|
|
if len(messages) > 0: |
|
msg = '\n\n'.join( |
|
url + '\n' + msg |
|
for url, msg in messages |
|
) |
|
if exists(config.sendmail): |
|
msg = MIMEText(msg) |
|
msg['From'] = config.sender |
|
msg['To'] = config.to |
|
msg['Subject'] = config.subject + ' %d/%d' % ( |
|
len(messages), len(config.urls)) |
|
p = Popen([config.sendmail, '-t'], stdin=PIPE) |
|
p.communicate(msg.as_string()) |
|
else: |
|
print msg |