Welcome, guest | Sign In | My Account | Store | Cart

Its easy to mess with Windows Service using Python.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import win32serviceutil

def service_info(action, machine, service):
    if action == 'stop': 
        win32serviceutil.StopService(service, machine)
        print '%s stopped successfully' % service
    elif action == 'start': 
        win32serviceutil.StartService(service, machine)
        print '%s started successfully' % service
    elif action == 'restart': 
        win32serviceutil.RestartService(service, machine)
        print '%s restarted successfully' % service
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4:
            print "%s is running normally" % service 
        else:
            print "%s is *not* running" % service 

if __name__ == '__main__':
    machine = 'cr582427-a'
    service = 'Zope23'
    action = 'start'
    service_info(action, machine, service)

This is extremely simple, all thanks to Mark Hammond's win32api. There are many more options available including install and remove service. These are covered in more details in Python Programming on Win32.

3 comments

tub4jxr 20 years, 4 months ago  # | flag

Problems changing modes. The code does not test whether or not the service actually changes from one state to another. I don't know if there is some return code that can be associated with the change of the service, but it would help if it was checked.

Frederico Chevitarese 11 years, 6 months ago  # | flag

Hi!!!

Thanks for the code... When i try this, the service stops successfully! But, when try to start the service, i get the message showing that has been started sucessfully but not !

Searching over the internet, i´ve found the solution ...

Use win32serviceutil.StartService(service) instead of win32serviceutil.StartService(service, machine) and it will work ;)

Thanks!

Amjad 6 years, 10 months ago  # | flag

if you want to start service on a remote machine then use the following code win32serviceutil.StartService(service_name, machine=machine_name)

else you would get the below error message or similar.... Traceback (most recent call last): win32serviceutil.StartService(service_name) File "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py", line 415, in StartService hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS) File "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py", line 80, in SmartOpenService name = win32service.GetServiceKeyName(hscm, name) pywintypes.error: (1060, 'GetServiceKeyName', 'The specified service does not exist as an installed service.')