A simple script designed to be run via an AT command to check the status of a service and attempt to restart it if necessary.

This requires Python for Windows extensions (http://sourceforge.net/projects/pywin32/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Utility for checking the status of windows service and
# attempting to perform a recovery if necessary.
#
# Designed to be run by AT/Scheduled Tasks.
#
# Emails can be sent to nominated staff when the
# service has failed and been recoved.
 
 
import win32serviceutil
import time
import smtplib
from win32api import GetDiskFreeSpace
from email.mime.text import MIMEText
 
 
servicename = 'Kiwi Syslog Server'
host = 'localhost'
mailserver = 'mail server IP'
sender = 'Source EMail'
recipient = [
    'Destination EMail 1',
    'Destination EMail 2']
 
 
def service_manager(action, machine, service):
    if action == 'stop':
        win32serviceutil.StopService(service, machine)
    elif action == 'start':
        win32serviceutil.StartService(service, machine)
    elif action == 'restart':
        win32serviceutil.RestartService(service, machine)
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4:
            servicestatus = 'RUNNING'
        else:
            servicestatus = 'NOT RUNNING'
        return servicestatus
 
 
def notify_mail(body):
    used, space = check_disk('d:')
    space = space / 1024.0 ** 3
    body = '%s \n\r\n\rDisk Free Space is %f GB' % (body, space)
    msg = MIMEText(body)
    msg['Subject'] = 'Syslog Server Status - %s' % checkservice
    msg['From'] = sender
    msg['To'] = ", ".join(recipient)
 
    s = smtplib.SMTP(mailserver)
    s.sendmail(sender, recipient, msg.as_string())
    s.quit()
 
 
def check_disk(disk):
    diskusage = GetDiskFreeSpace(disk)
    bytes_used = diskusage[0] * diskusage[1] * diskusage[3]
    bytes_available = diskusage[0] * diskusage[1] * diskusage[2]
    return bytes_used, bytes_available
 
 
# Main script starts below
 
checkservice = service_manager('status', host, servicename)
 
 
if checkservice == 'NOT RUNNING':
    i = 0
    while (checkservice == 'NOT RUNNING' and i < 10):
        notify_mail('The syslog server is %s. Trying to recover.' % checkservice)
        service_manager('start', host, servicename)
        time.sleep(30)
        checkservice = service_manager('status', host, servicename)
        i += 1
 
    if i == 10:
        #print 'Unable to recover the service'
        notify_mail('Unable to recover the service. Please investigate.')
    else:
        #print 'Service is %s' % checkservice
        notify_mail('The syslog server is now %s' % checkservice)
Windows Service Status Checker
Tagged on:         

Leave a Reply