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!
if(len(sys.argv) < 2) :
print (‘Usage : python webup.py http://example.com’)
self.url = sys.argv
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’)
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))
# Log error
# Get latest tail of access.log
# Attach to e-mail?
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():
retval = p.wait()
if __name__ == ‘__main__’:
checker = WebUp()