您可以使用PythonWMI模块 http://timgolden.me.uk/python/wmi/index.html为此(安装PyWin32 扩展 http://starship.python.net/crew/mhammond/win32/Downloads.html以及运行这些脚本之前的 WMI 模块)。以下是如何配置与硬件设备通信的方法:
import wmi
# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adaptor
nic = nic_configs[0]
# IP address, subnetmask and gateway values should be unicode objects
ip = u'192.168.0.11'
subnetmask = u'255.255.255.0'
gateway = u'192.168.0.1'
# Set IP address, subnetmask and default gateway
# Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
nic.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
nic.SetGateways(DefaultIPGateway=[gateway])
以下是如何恢复自动获取 IP 地址(通过 DHCP):
import wmi
# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adaptor
nic = nic_configs[0]
# Enable DHCP
nic.EnableDHCP()
注意:在生产脚本中,您应该检查返回的值启用静态() http://msdn.microsoft.com/en-us/library/aa390383%28v=VS.85%29.aspx, 设置网关() http://msdn.microsoft.com/en-us/library/aa393301%28v=VS.85%29.aspx and 启用 DHCP() http://msdn.microsoft.com/en-us/library/aa390378%28v=VS.85%29.aspx。 (“0”表示成功,“1”表示需要重新启动,其他值在方法名称链接到的 MSDN 页面上进行了描述。注意:对于 EnableStatic() 和 SetGateways(),错误代码以列表形式返回)。
有关 Win32NetworkAdapterConfiguration 类所有功能的完整信息也可以在 MSDN 上找到的 http://msdn.microsoft.com/en-us/library/aa394217%28VS.85%29.aspx.
注意:我使用 Python 2.7 对此进行了测试,但由于 PyWIn32 和 WMI 模块可用于 Python 3,我相信您应该能够通过删除字符串文字前面的“u”来使其适用于 Python 3。