Last active
January 31, 2019 14:43
-
-
Save mos3abof/4771874 to your computer and use it in GitHub Desktop.
Poor Man's Guide for Monitoring a Website Using Python on Ubuntu and Restarting Apache when it is down.
http://www.mos3abof.com/poor-man-website-python-monitor.html
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# Import DateTime | |
from datetime import datetime, timedelta, date | |
# Import urllib | |
import urllib | |
# Importing utilities from Fabric | |
from fabric.api import env, sudo | |
# Import email stuff | |
import smtplib | |
from email.MIMEMultipart import MIMEMultipart | |
from email.MIMEBase import MIMEBase | |
from email.MIMEText import MIMEText | |
from email import Encoders | |
# For debugging purposes | |
import traceback | |
# Import Logging lib | |
import logging | |
# Setting up Logging | |
current_date = date.today() | |
current_log_file_name = '/opt/fab_logs/' + current_date.isoformat() + '.log' | |
logging.basicConfig( format = '%(asctime)s [%(levelname)s] %(message)s', | |
filename = current_log_file_name, | |
level = logging.INFO) | |
# Defining the env.hosts | |
env.hosts = ['username@server-address'] | |
env.passwords = {'username@server-address' : 'passoword' } | |
# The function that actually sends email | |
def mail(to, subject, text, gmail_user, gmail_pwd): | |
''' | |
Sends mail using gmail | |
''' | |
msg = MIMEMultipart() | |
# Setting up message data | |
msg['From'] = 'alterts@yoursite.com' | |
msg['To'] = to | |
msg['Subject'] = subject | |
msg.attach(MIMEText(text)) | |
# Opening the connection with Gmail SMTP server | |
mailServer = smtplib.SMTP("smtp.gmail.com", 587) | |
mailServer.ehlo() | |
mailServer.starttls() | |
mailServer.ehlo() | |
mailServer.login(gmail_user, gmail_pwd) | |
# Actual sending of the email | |
mailServer.sendmail(gmail_user, to, msg.as_string()) | |
# Closing the connection | |
# Should be mailServer.quit(), but that crashes | |
mailServer.close() | |
# Alerting the DevOps Team | |
def alert_dev_team(message = ''): | |
''' | |
This functions emails the DevOps Team that there is a downtime | |
''' | |
# Constructing the email message | |
subject = 'YOUR WEBSITE IS DOWN' | |
email_body = 'YOUR WEBSITE IS DOWN. \nTime now is {} \n{}'.format(date.today().isoformat(), message) | |
gmail_user = 'GMAIL-USERNAME' | |
gmail_pwd = 'PASSWORD' | |
logging.debug("Constructed Email message") | |
recepient = 'alerts@yoursite.com' | |
# Sending the message | |
mail(recepient, subject, email_body, gmail_user, gmail_pwd) | |
logging.debug("Finished sending all messages") | |
# Let the magic begin | |
def restart_apache(): | |
''' | |
Checks if Apache2 server on YOUR WEBSITE is accessible through the web. | |
If not it attemptes to restart it and alert the Dev Team. | |
It should be added to cron to run every 5 minutes like this : | |
*/5 * * * * /usr/bin/fab -f /opt/fabfile.py restart_apache | |
''' | |
try: | |
logging.info("The script was invoked by the cron") | |
# Open the site using urllib | |
result = urllib.urlopen("http://www.yourwebsite.com").getcode() | |
# if the alue of the respsonse is not 200 then raise an error | |
if not result == 200: | |
raise ValueError | |
# Log the attempt and successful result | |
logging.info("The result came back {}".format(result)) | |
logging.info("Everything seems fine! Over and out!") | |
# if we don't get a response at all or the value is not 200 OK then start the mechanism | |
except: | |
# Something with the wsbite is not right, attempt to restart the Apache server | |
logging.error("Houston, we have got a problem! Attempting an Apache restart") | |
logging.debug(traceback.format_exc()) | |
# setup the message to email to DevOps team | |
message = 'Restart attempt complete. Everything should be fine now' | |
try: | |
# restart apache using sudo | |
sudo('apache2ctl restart') | |
except: | |
# If the restart attempt fails we should know! | |
logging.error("WE FAILED! The script couldn't restart the Apache. Human intervention needed!") | |
logging.error(traceback.format_exc()) | |
message = "WE FAILED! The script couldn't restart the Apache. Human intervention needed!" | |
try: | |
# Attempt to alert the DevOps team | |
alert_dev_team(message) | |
logging.info("Sending an email to alerts@yoursite.com") | |
except: | |
logging.error('Tried sending an email and failed!') | |
logging.info("Restart attempt complete. Everything should be fine now") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment