问题
I am attempting to get a list of services that are running on a windows machine with python.
My Code:
import wmi
c = wmi.WMI()
wql = "SELECT * FROM Win32_Service WHERE State = ""Running"""
for x in c.query(wql):
print(x)
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.
Error:
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:
wql = "SELECT * FROM Win32_Service WHERE State = ""Running"""
results to an invalid WQL query (checked using print(wql)
)
SELECT * FROM Win32_Service WHERE State = Running
You need
wql = 'SELECT * FROM Win32_Service WHERE State = "Running"'
which results to a valid WQL query (read WHERE Clause docs)
SELECT * FROM Win32_Service WHERE State = "Running"
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'"
来源:https://stackoverflow.com/questions/50864409/using-python-and-wmi-queries-to-get-a-list-of-running-services