Created
January 11, 2016 20:56
-
-
Save jasonraimondi/ee6205992d508ca1fa3f to your computer and use it in GitHub Desktop.
Website monitoring script to alert you when your site is down
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
# pip install requests | |
# run it on a cron, the more clients you are looking, the longer the script takes | |
# currently it delays for 15 seconds between successful pings | |
import time | |
import pprint | |
## list of sites to track along with email address to send the alert | |
clients = [ | |
"http://www.website1.com", | |
"http://www.website2.com", #etc | |
] | |
down = [] | |
up = [] | |
def send_email(sites_down): | |
''' function to monitor up time ''' | |
import smtplib | |
gmail_user = 'username@gmail.com' | |
gmail_pwd = 'password' | |
FROM = gmail_user | |
TO = 'send-alert-to@gmail.com' if type('send-alert-to@gmail.com') is list else ['send-alert-to@gmail.com'] | |
SUBJECT = '[WEBSITES DOWN]' | |
TEXT = { | |
"Sites Down": sites_down | |
} | |
# Prepare actual message | |
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s | |
""" % (FROM, ", ".join(TO), SUBJECT, TEXT) | |
try: | |
server = smtplib.SMTP("smtp.gmail.com", 587) | |
server.ehlo() | |
server.starttls() | |
server.login(gmail_user, gmail_pwd) | |
server.sendmail(FROM, TO, message) | |
server.close() | |
print 'Successfully sent the mail' | |
print up | |
except: | |
print "Failed to send mail" | |
def site_check(): | |
''' function to monitor up time ''' | |
import requests | |
for client in clients: | |
try: | |
r = requests.get(client) | |
if r.status_code == requests.codes.ok: | |
up.append(client) | |
time.sleep(15) | |
else: | |
down.append(client) | |
except requests.ConnectionError: | |
down.append(client) | |
if not down: | |
print "All Good" | |
print up | |
else: | |
send_email(down) | |
site_check() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment