Skip to content

Instantly share code, notes, and snippets.

@ibeex
Created November 28, 2011 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ibeex/1400432 to your computer and use it in GitHub Desktop.
Save ibeex/1400432 to your computer and use it in GitHub Desktop.
Simple web server watchdog
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Simple web server watchdog, edit constants and stop start commands
preferably run with daemon
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
"""
# Import's
import urllib2
import subprocess
import time
import logging
import os
import datetime
# Constants
LOG_FILE = 'log/watchdog.log'
URL = 'url to test'
EXPECTING = 'Some text'
# Opening log
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
filename=LOG_FILE)
def restart(messge):
"""Restart service and logg message"""
subprocess.check_call('/etc/init.d/server stop')
subprocess.check_call('/etc/init.d/server start')
logging.info('Restart {0}'.format(message))
time.sleep(60)
def main():
"""Main"""
while True:
hour = datetime.datetime.now().hour
try:
tw = urllib2.urlopen(URL, timeout=5)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, e:
restart(e)
continue
if tw.code != 200:
restart('Wrong return')
continue
if EXPECTING not in tw.read():
restart('Missig page')
continue
tw.close()
if 7 < hour < 18: #working hours check every 10s
time.sleep(10)
else:
time.sleep(30)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment