Python WMI 调用在 Windows 7 下不起作用

标签 python wmi win32com

我在 Windows 7 下的 Python 中使用 WMI(通过 win32com)遇到了一个棘手的问题。我一直无法找到解决方案。

这是我的代码:

from win32com.client import GetObject

def get_printers(computer):
    """ Get a list of printers from the specified computer name. """
    wmiservice = GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + computer + r"\root\cimv2")
    return wmiservice.ExecQuery("Select * from Win32_Printer")

for printer in get_printers("ps2"):
    print printer.Name

这在 Windows XP 下效果很好。但是如果我在 Windows 7 下运行它会失败:

Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Python27\sample\temp2.py", line 8, in <module>
    for printer in get_printers("ps2"):
  File "C:\Python27\sample\temp2.py", line 5, in get_printers
    wmiservice = GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + computer + r"\root\cimv2")
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 72, in GetObject
    return Moniker(Pathname, clsctx)
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 87, in Moniker
    moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
com_error: (-2147024891, 'Access is denied.', None, None)

我在 Win 7 中尝试了所有我能想到的方法:禁用防火墙(没有病毒扫描程序)、确保 DCOM 已启用、确保 WMI 已启用以及禁用 UAC。任何帮助将不胜感激。

注意:我在 Windows 7 Ultimate x86(和 Windows XP SP3)下使用 Python 2.7.1 和 pywin32 build 215。

最佳答案

事实证明,问题与 DCOM/WMI/UAC/Firewall 无关。真正令人惊讶的是,当这些故障发生时,Win 7 PC 的事件日志中根本没有任何报告。

我注意到,与最初的问题一样,来自 Win 7 的传出连接报告访问被拒绝。但我也注意到传入 Win 7 PC 的连接(与上面相同的 python 脚本)报告 RPC 服务器不可用。其他 PC(不是 Win 7)的 PC 也会在事件日志中报告 kerberos 错误(ID 4)。

问题原来是我们域中的事件目录有些奇怪,特别是在这台 Win 7 PC 上。出于某种原因,事件目录错误地认为有多台 PC 具有此名称 - 这是 kerberos 事件日志的来源。

有效的修复方法是:将 Win 7 PC 从域中移除,将 PC 更改为新名称,然后将 PC 放回域中。

关于Python WMI 调用在 Windows 7 下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4972398/

相关文章:

python docker 如何打印脚本的返回码以了解测试脚本是否通过或失败

c# - 我怎样才能在 C# 中获得免费的 USB 端口?

python - 如何评估字符串并将其添加到 numpy 数组元素

powershell - 将 CimInstance 数组传递给 CimMethod

c# - C# COM DLL 中的 ManagementObject 泄漏

python - win32com 获取可用应用程序列表

python-2.7 - 使用 Python 从 Outlook 2010 获取附件

excel - 如何使用 Python 在 VBA 对话框上禁用或自动选择 'OK'(Application.DisplayAlerts = False 不起作用)

python - txt文件中的熵

python - 在 azure 上安装附加组件以与 python webapp 一起使用