Search code examples
pythonwindowsservice

List local running services on Windows 10 using Python?


All I need to do is create a program that lists all running services on my Windows machine. I have tried a number of methods including psutil to no avail. I have since tried to simplify it by just trying to execute the "net stat" command. It works, but the output is garbled. Is there anyway to save this to a text file nice and neat? Also, I'd like to append the word 'Running' next to each line. When I try to add that I get the following error:

File "./Python37/test3.py", line 3, in print(str(result.stdout + 'running')) TypeError: can't concat str to bytes

Here is my code so far:

import subprocess
result = subprocess.run(['net', 'start'], stdout=subprocess.PIPE)
print(str(result.stdout + 'running'))

Solution

  • Use EnumServicesStatus API like this :

    import win32con
    import win32service
    
    def ListServices():
        resume = 0
        accessSCM = win32con.GENERIC_READ
        accessSrv = win32service.SC_MANAGER_ALL_ACCESS
    
        #Open Service Control Manager
        hscm = win32service.OpenSCManager(None, None, accessSCM)
    
        #Enumerate Service Control Manager DB
        typeFilter = win32service.SERVICE_WIN32
        stateFilter = win32service.SERVICE_STATE_ALL
    
        statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
    
        for (short_name, desc, status) in statuses:
            print(short_name, desc, status) 
    
    ListServices();
    
    • win32service and win32con is part of pywin32 opensource project which you can download the lastest version here .