2015년 9월 4일 금요일

How to check Windows System Service status with Python


You can check Windows system service status using Python.

Using psutil

>>> import win32serviceutil
>>> win32serviceutil.QueryServiceStatus("Service_Name")
(272, 4, 7, 0, 0, 0, 0) # 4 means it's running
>>> win32serviceutil.QueryServiceStatus("Service_Name")
(272, 1, 0, 0, 0, 0, 0) # 1 means it's stopped

Using wmi

You can lookup with conditions like StartMode and State. Following code enumerates services whose StartMode is "Disabled" and current State is "Stopped".

>>> import wmi
>>> c=wmi.WMI()
>>> c.Win32_Service(StartMode="Disabled", State="Stopped")
[<_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="aspnet_state">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="clr_optimization_v2.0.50727_32">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="clr_optimization_v2.0.50727_64">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="Mcx2Svc">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetMsmqActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetPipeActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetTcpActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetTcpPortSharing">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="RemoteAccess">]

Check if specific service is running or not. Empty array is returned if the service is not running.

>>> c.Win32_Service(Name="Netlogon", State="Running")
[]