From d2a371b03b2dc3afd98715ee4ae64880c6ec4f34 Mon Sep 17 00:00:00 2001 From: Corey Schafer Date: Tue, 26 Feb 2019 20:22:50 -0700 Subject: [PATCH] Website Monitoring Script --- Python/Site-Monitor/monitor.py | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/Site-Monitor/monitor.py diff --git a/Python/Site-Monitor/monitor.py b/Python/Site-Monitor/monitor.py new file mode 100644 index 0000000..9bdcd46 --- /dev/null +++ b/Python/Site-Monitor/monitor.py @@ -0,0 +1,51 @@ +import os +import smtplib +import requests +# import logging +from linode_api4 import LinodeClient, Instance + +EMAIL_ADDRESS = os.environ.get('EMAIL_USER') +EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') +LINODE_TOKEN = os.environ.get('LINODE_TOKEN') + +# logging.basicConfig(filename='PATH_TO_DESIRED_LOG_FILE', +# level=logging.INFO, +# format='%(asctime)s:%(levelname)s:%(message)s') + + +def notify_user(): + with smtplib.SMTP('smtp.gmail.com', 587) as smtp: + smtp.ehlo() + smtp.starttls() + smtp.ehlo() + + smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) + + subject = 'YOUR SITE IS DOWN!' + body = 'Make sure the server restarted and it is back up' + msg = f'Subject: {subject}\n\n{body}' + + # logging.info('Sending Email...') + smtp.sendmail(EMAIL_ADDRESS, 'INSERT_RECEIVER_ADDRESS', msg) + + +def reboot_server(): + client = LinodeClient(LINODE_TOKEN) + my_server = client.load(Instance, 376715) + my_server.reboot() + # logging.info('Attempting to reboot server...') + + +try: + r = requests.get('https://example.com', timeout=5) + + if r.status_code != 200: + # logging.info('Website is DOWN!') + notify_user() + reboot_server() + else: + # logging.info('Website is UP') +except Exception as e: + # logging.info('Website is DOWN!') + notify_user() + reboot_server()