您可以使用Python WMI模块来执行此操作(在运行这些脚本之前安装PyWin32扩展和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()
注意:在生产脚本中,您应该检查由EnableStatic() , SetGateways()和EnableDHCP()返回的值。 ('0'表示成功,'1'表示重新启动,其他值在方法名称链接到的MSDN页面上描述。注意:对于EnableStatic()和SetGateways(),错误代码以列表形式返回。
有关Win32NetworkAdapterConfiguration类的所有功能的完整信息也可以在MSDN上找到 。
注意:我用Python 2.7测试了这个,但是因为PyWIn32和WMI模块可用于Python 3,我相信你应该能够通过从字符串文字之前去掉“u”来得到Python 3的工作。