您可以使用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的工作。