Skip to content

Instantly share code, notes, and snippets.

@eliezerfot123
Created August 9, 2016 18:47
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 eliezerfot123/2d5b6050754a8e50a809d5d3aaff0c07 to your computer and use it in GitHub Desktop.
Save eliezerfot123/2d5b6050754a8e50a809d5d3aaff0c07 to your computer and use it in GitHub Desktop.
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 = ['eliezerfot123@gmail.com']
msg = MIMEMultipart()
msg['Subject'] = 'OFFLINE '+str(urldown)
msg['From'] = 'eliezerfot123@gmail.com '
msg['To'] = 'eliezerfot123@gmail.com'
body = str(message)
msg.attach(MIMEText(body, 'plain'))
try:
smtpObj = SMTP('smtp.gmail.com')
smtpObj.login('eliezerfot123@gmail.com','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