I’m currently writing a python script to analyse web servers for connectivity. Due to various issues I have encountered whilst running this and other sites such as DDOS attacks and Mysql failing due to lack of memory. So far it probes a given site to see if it is active. If it detects connectivity it will attempt to restart the apache server.
One cool thing I learnt whilst doing this was correctly logging the output of the script using the python logging lib. The next update in this project will be to add a feature whereby it will e-mail and attach these logs for viewing by an admin should the site be down. Another idea I’m mulling over is the ability to tail the access log of apache and detect if a site is currently under attack. Then hopefully update the IPTables to block that address.
The code so far – Note this is still in development!
import requests import sys import subprocess import logging class WebUp(): def __init__(self): if(len(sys.argv) < 2) : print ('Usage : python webup.py http://example.com') sys.exit() self.url = sys.argv[1] logging.basicConfig(filename='/home/usrname/WebUp.log',format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%d/%m/%Y %I:%M:%S %p') def checkURL(self): try: r = requests.head(self.url) if r.status_code == 200: logging.info("Website OK" + str(r.status_code)) return r.status_code == 200 except ( requests.exceptions.RequestException) as e: # print("Connection Error " + str(e)) self.handleError(e) def handleError(self,e): # Log error # Get latest tail of access.log # Attach to e-mail? # Exit logging.warning('Website is down due to:' + str(e)) # restart apache logging.info("Attempting to restart apache2 service") p = subprocess.Popen("sudo service apache2 restart", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print (line) retval = p.wait() self.checkURL() if __name__ == '__main__': checker = WebUp() checker.checkURL()