public
Last active

Simple script to check when your site changes status codes

  • Download Gist
gistfile1.py
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
import pickle, pprint, time, os
import httplib
import smtplib
 
 
def emailAlert(alert,subject='You have an alert'):
fromaddr = "youremail@domain.com"
toaddrs = "youremail@domain.com"
 
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nSubject: %s\r\nTo: %s\r\n\r\n"
% (fromaddr,subject,toaddrs))
msg = msg + alert
 
server = smtplib.SMTP('localhost')
# server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
 
 
def internetUp():
data = []
urls = ['www.google.com','www.yahoo.com']
try:
for url in urls:
conn = httplib.HTTPConnection(url)
conn.request("HEAD", "/")
res = conn.getresponse()
data.append(res.status)
# print res.status, res.reason, url
if data[0] != 200 and data[1] != 200:
return False
exit('Internet might be down!')
else:
return True
except:
exit('Internet is defeinitely down!')
 
 
def isSiteup(urls):
 
data = {}
data['timestamp'] = time.time()
for url in urls:
conn = httplib.HTTPConnection(url)
conn.request("HEAD", "/")
res = conn.getresponse()
data[url] = res.status
# print res.status, res.reason, url
 
if url in data1:
if data1[url] != res.status:
alertMessage = ("%s has changed from %s to %s" % (url, data1[url], res.status))
alertSubject = ("%s has changed status" % (url))
emailAlert(alertMessage,alertSubject)
# print 'Sending an email!'
#else:
# print url, 'is still the same', data1[url], 'and', res.status
 
output = open('data.pkl','wb')
pickle.dump(data, output)
output.close()
 
 
 
# Check to see if the internet is up
internetUp()
 
if os.path.isfile('data.pkl'):
pklFile = open('data.pkl','rb')
data1 = pickle.load(pklFile)
# pprint.pprint(data1)
 
elapsedTime = time.time() - data1['timestamp']
elapsedMinutes = elapsedTime/60
 
#if elapsedMinutes > 2:
# print 'It\'s been longer than two minutes'
else:
data1 = {}
 
# Urls to check
urls = ['www.nixtutor.com',
'www.marksanborn.net',
'faceoffshow.com',
'rocketship.it',
'jaderobbins.com']
 
# Run the checks
isSiteup(urls)
 
 
#pklFile.close()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.