从WMI com对象调用Win32网络适配器配置例程

2024-06-07 01:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

提前感谢你的帮助。我试图使用win32com模块设置网络接口的ip地址,但无法这样做。我试了很多次,但没能找到问题的答案。下面是我正在运行的代码: import win32com.client

obj=win32com.client.Dispatch公司("WbemScripting.SWbemLocator“)

wmobj=对象连接服务器(“localhost”,“root\cimv2”)

诺比=wmobj.ExecQuery(“从Win32 NetworkAdapterConfiguration中选择*”)

对于nobj中的n:

print n.Caption

n.SetMTU('9000')

当我运行此代码时,它会出现以下错误:

回溯(最近一次呼叫): 文件“”,第3行,输入 n、 SetMTU('9000') 文件“C:\Python27\lib\site packages\win32com\client\动态.py“,第505行,ingetattr ret=self.oleobj。调用(返回.dispid,0,调用类型,1) com错误:(-2147352567,“发生异常。”,(0,u'SWbemObjectEx',u'Invalid method',None,0,-2147217362),None)

我做了更多的调试,发现我可以访问Win32Networking类的任何变量,但每当我试图调用该类的任何方法时,它都会返回相同的错误。在


Tags: 模块文件答案代码importipclientnone
3条回答

我没有太多使用win32com的经验,但是SetMTU方法可能没有实现。根据Win32_NetworkAdapterConfiguration class的MSDN文档,该方法是“不支持的”。我在XP中失败了。在

请注意,使用win32com,只需访问一个属性就可以调用它:

>>> import win32com.client
>>> wmobj = obj.ConnectServer("localhost","root\cimv2")
>>> nobj = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration")
>>> n = nobj[10]  #my wireless interface
>>> n.ReleaseDHCPLease  #invoked
0
>>> n.RenewDHCPLease
0

尝试正常调用它将导致尝试调用整数返回值,这将引发一个TypeError。但是,您可以首先包装这样一个方法,使其成为一个普通的Python调用:

^{pr2}$

编辑:

在上面链接的页面的用户贡献区域中,搜索必须从类访问的静态方法列表,包括SetMTU。以下是获取课程的方法:

>>> NetAdapterConfig = wmobj.Get("Win32_NetworkAdapterConfiguration")
>>> NetAdapterConfig._FlagAsMethod('SetMTU')

有关返回值的含义,请参见the docs。虽然我不太明白这个方法在静态上下文中的作用。在


下面是一个使用标准库的winreg更新注册表的示例:

import winreg

nid = n.SettingID
MTU = 1500

path = r'SYSTEM\CurrentControlSet\Services\TCPIP\Parameters\Interfaces\\'+ nid 
sam = winreg.KEY_ALL_ACCESS
adapter = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, sam)
winreg.SetValueEx(adapter, 'MTU', None, winreg.REG_DWORD, MTU)

我刚试过FlagAsMethod

如建议,对于Win32_Process类,例如:

proc10 = GetObject(pos).ExecQuery("Select * from Win32_Process")[10]
proc10._FlagAsMethod('GetOwner')
proc10.GetOwner()
# >> 0

但是,我期待domain\user等等,而且,我也能写

^{pr2}$

但效果是一样的。在

我发布了here一个在我的案例中有效的方法。我只是想知道SetMTU是否使用_FlagAsMethod技巧接收到正确的值。在

我遇到了类似的问题,并找到了调用Win32 NetworkAdapterConfiguration对象的这些方法的方法。这里我没有直接使用这些方法,而是将所有输入参数包装到一个spawn实例中。它看起来像是有线的,但有效。在

import win32com.client
objLocator = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objService = objLocator.ConnectServer(".","root\cimv2")
nobj = objService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
obj = nobj[0]

## here is the strange part. 
obj_method = obj.Methods_("SetWINSServer")
obj_in_param = obj_method.inParameters.SpawnInstance_()
obj_in_param.WINSPrimaryServer = "127.0.0.1"
obj_in_param.WINSSecondaryServer = "127.0.0.2"
#invoke the SetWINServer method, and it worked.
obj.ExecMethod_("SetWINSServer", obj_in_param)

几乎所有这些Win32网络适配器配置方法都可以这样使用。 但是,“SetMTU”不能,可能是因为“不支持这个方法”,我在windows2008r2上尝试了一下,却得到了同样的错误。 它说这里不支持SetMTU。 http://msdn.microsoft.com/en-us/library/windows/desktop/aa393463(v=vs.85).aspx

相关问题 更多 >