使用Python和WMI查询获取正在运行的服务列表

时间:2018-06-14 19:15:26

标签: python windows wmi wmi-query

我正在尝试使用python获取在Windows机器上运行的服务列表。

我的代码:

import wmi
c = wmi.WMI()    
wql = "SELECT * FROM Win32_Service WHERE State = ""Running"""
for x in c.query(wql):
    print(x)

我收到错误,我不明白为什么。我的脚本中有一些其他的wql语句,它们似乎工作正常。

错误:

Traceback (most recent call last):
  File "C:/Users/i861470/Desktop/Scripts/test.py", line 79, in <module>
    for x in c.query(wql):
  File "C:\Users\i861470\Desktop\Scripts\venv\lib\site-packages\wmi.py", line 1009, in query
    return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
  File "C:\Users\i861470\Desktop\Scripts\venv\lib\site-packages\wmi.py", line 1009, in <listcomp>
    return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
  File "C:\Users\i861470\Desktop\Scripts\venv\lib\site-   packages\win32\com\client\dynamic.py", line 280, in __getitem__
    return self._get_good_object_(self._enum_.__getitem__(index))
  File "C:\Users\i861470\Desktop\Scripts\venv\lib\site-packages\win32\com\client\util.py", line 41, in __getitem__
    return self.__GetIndex(index)
  File "C:\Users\i861470\Desktop\Scripts\venv\lib\site-packages\win32\com\client\util.py", line 62, in __GetIndex
    result = self._oleobj_.Next(1)
win32.types.com_error: (-2147217385, 'OLE error 0x80041017', None, None)

1 个答案:

答案 0 :(得分:1)

wql = "SELECT * FROM Win32_Service WHERE State = ""Running"""

导致无效的WQL查询(使用print(wql)检查)

SELECT * FROM Win32_Service WHERE State = Running

您需要

wql = 'SELECT * FROM Win32_Service WHERE State = "Running"'

导致有效的WQL查询(阅读WHERE Clause docs)

SELECT * FROM Win32_Service WHERE State = "Running"

顺便说一句,您可以在"Running"子句中使用字符串文字,例如'Running'WHERE。因此,以下WQL查询也起作用:

wql = "SELECT * FROM Win32_Service WHERE State = 'Running'"