WxRob87
WxRob87

Reputation: 55

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

Upvotes: 3

Views: 11385

Answers (2)

user459872
user459872

Reputation: 24562

Starting from psutil 4.2.0 onwards you can list and query the windows services using following APIs.

Usage:

>>> 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>,
 ...]

Usage:

>>> import psutil
>>> 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'}

Upvotes: 4

Mojtaba Tajik
Mojtaba Tajik

Reputation: 1733

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 .

Upvotes: 4

Related Questions