使用 Python 和 WMI 查询获取正在运行的服务列表 [英] Using Python and WMI Queries to get a list of running services

查看:40
本文介绍了使用 Python 和 WMI 查询获取正在运行的服务列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to get a list of services that are running on a windows machine with python.

我的代码:

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

我收到一个错误,我不明白为什么.我的脚本中还有其他一些 wql 语句,它们似乎运行良好.

I am getting an error and I do not understand why. I have a few other wql statements in my script and they seem to be working fine.

错误:

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)

推荐答案

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

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

results to an invalid WQL query (checked using print(wql))

SELECT * FROM Win32_Service WHERE State = Running

你需要

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

结果为有效的 WQL 查询(阅读 WHERE 子句 docs)

which results to a valid WQL query (read WHERE Clause docs)

SELECT * FROM Win32_Service WHERE State = "Running"

顺便说一句,您可以在 WHERE 子句中使用字符串文字,例如 "Running"'Running'.因此,以下 WQL 查询同样有效:

BTW, you may use string literals, such as "Running" or 'Running', in a WHERE clause. Hence, the following WQL query works as well:

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

这篇关于使用 Python 和 WMI 查询获取正在运行的服务列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆