Search code examples
pythonwindowsservicewmi

How to check if a service is running using WMI in Python?


I am new to Python and coding in general. I am trying to detect if a certain service is running, and if running, to stop it and restart it. If it doesn't exist, throw an exception and exit.

I have the following:

import wmi

c = wmi.WMI()

for service in c.Win32_Service():
    if service.Name == 'genericservice':
        service.StopService()

I borrowed that code from another script that we had existing. However, how do I add a conditional statement to check if the service is even running in the first place? And then to exit with an exception if it's not running at all?

Please advise. Thank you!


Solution

  • This can easily be done using WQL in win32com.client module.

    For example,

    from win32com.client import GetObject
    WMI = GetObject('winmgmts:')
    
    if len(WMI.ExecQuery('select * from Win32_Process where Name like "%s%s"' % ("process_name",'%'))) > 0:
        pass 
    

    To do so in your way, do something like this using WQL to check if that service is indeed running or not.

    You can see the tutorial if it helps.