Skip to content

Instantly share code, notes, and snippets.

@sanand0
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanand0/11087397 to your computer and use it in GitHub Desktop.
Save sanand0/11087397 to your computer and use it in GitHub Desktop.
A simple website monitor

A simple website monitor.

  1. Edit config.py and add a list of URLs.
  2. Set up a cron job to run python monitor.py periodically
sender = 'monitor@gramener.com'
to = 's.anand@gramener.com'
subject = 'Site monitoring errors'
sendmail = '/usr/sbin/sendmail'
urls = (
'http://gramener.com/',
'http://blog.gramener.com/',
)
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment