简体   繁体   中英

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'))

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 .

From psutil 4.2.0 on wards you can list and query the windows services using psutil.win_service_iter() andpsutil.win_service_get(name) functions.

>>> import psutil
>>> list(psutil.win_service_iter())
    [<WindowsService(name=AeLookupSvc, display_name=Application Experience) at 38850096>,
     <WindowsService(name=ALG, display_name=Application Layer Gateway Service) at 38850128>,
     <WindowsService(name=APNMCP, display_name=Ask Update Service) at 38850160>,
     <WindowsService(name=AppIDSvc, display_name=Application Identity) at 38850192>,
     ...
    ]
>>> s = psutil.win_service_get('alg')
>>> s.as_dict()

    {'binpath': 'C:\\Windows\\System32\\alg.exe',
     'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
     'display_name': 'Application Layer Gateway Service',
     'name': 'alg',
     'pid': None,
     'start_type': 'manual',
     'status': 'stopped',
     'username': 'NT AUTHORITY\\LocalService'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM