Created
August 9, 2016 18:47
-
-
Save eliezerfot123/2d5b6050754a8e50a809d5d3aaff0c07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import httplib | |
import urllib2 | |
from smtplib import SMTP | |
from email.MIMEMultipart import MIMEMultipart | |
from email.MIMEText import MIMEText | |
## defining email alert message | |
def email_alert(message, urldown): | |
toaddrs = ['[email protected]'] | |
msg = MIMEMultipart() | |
msg['Subject'] = 'OFFLINE '+str(urldown) | |
msg['From'] = '[email protected] ' | |
msg['To'] = '[email protected]' | |
body = str(message) | |
msg.attach(MIMEText(body, 'plain')) | |
try: | |
smtpObj = SMTP('smtp.gmail.com') | |
smtpObj.login('[email protected]','password') | |
smtpObj.sendmail('Recipient Name ', toaddrs, msg.as_string()) | |
smtpObj.quit() | |
print 'Alert Email sent' | |
except Exception,e: | |
print 'Error: unable to send email',e | |
## defining dictionary of url to check | |
urls=[ | |
'google.com', | |
'yahoo.com', | |
] | |
## first we check if internet is available | |
try: | |
urllib2.urlopen("http://google.com", timeout=2) | |
for url in urls: | |
try: | |
## check if we get url headers | |
conn = httplib.HTTPConnection(url) | |
conn.request("HEAD", "/") | |
r1 = conn.getresponse() | |
## response is ok | |
## check if we get a server error 5xx | |
if str(r1.status).startswith('5'): | |
email_alert(str(r1.status)+ ' '+str(r1.reason), url) | |
print url, '--- OFFLINE: ',r1.status, r1.reason | |
else: | |
print url,' ONLINE: ',r1.status, r1.reason | |
except Exception,e: | |
## response get an exception, print it and send alert email | |
print url, '--- OFFLINE: ',str(e) | |
email_alert(str(e), url) | |
print '-'*30 | |
except urllib2.URLError: | |
# there is no connection | |
print 'there is no internet connection' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment