为了方便能在寝室和实验室之间往返后更改电脑ip,参考了blogjava中 的文章,并添加了测试网络连接小功能。用py2exe打包为exe文件。创建快捷方式,然后以管理员身份运行(这个很重要,要不然ip改不了)。
# -*- coding: cp936 -*-
import wmi
import urllib2
IPV4_25 = {'arrIPAddresses':['10.110.87.19'], 'arrSubnetMasks':['255.255.255.0'],
'arrDefaultGateways':['10.110.87.1'], 'arrGatewayCostMetrics':[1],
'arrDNSServers':['10.10.0.21',]}
IPV4_CAOZHU = {'arrIPAddresses':['10.214.26.129'], 'arrSubnetMasks':['255.0.0.0'],
'arrDefaultGateways':['10.214.26.1'], 'arrGatewayCostMetrics':[1],
'arrDNSServers':['10.10.0.21',]}
def connect_and_test(objNicConfig, ipv4):
return_value = objNicConfig.EnableStatic(
IPAddress = ipv4['arrIPAddresses'],
SubnetMask = ipv4['arrSubnetMasks']
)
'''
These can be used for test, and work well with the under methods.
if returnValue[0] == 0: #0 means success and no reboot is required
print ' 成功设置IP'
elif returnValue[0] == 1: #1 means success and reboot is required
print ' 成功设置IP'
intReboot += 1
else: #other results means failure.
print '修改IP失败(IP设置发生错误)'
exit()
'''
return_value = objNicConfig.SetGateways(
DefaultIPGateway = ipv4['arrDefaultGateways'],
GatewayCostMetric = ipv4['arrGatewayCostMetrics']
)
return_value = objNicConfig.SetDNSServerSearchOrder(
DNSServerSearchOrder = ipv4['arrDNSServers']
)
#此处设备超时时间,因为目测网络连接消耗时间有几秒。没有作进一步的时间分析测试。
try:
urllib2.urlopen('http://www.cc98.org', timeout=5)
except urllib2.URLError:
return False
return True
def main():
wmiService = wmi.WMI()
colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
if len(colNicConfigs)<1:
print '没有找到合适的网络适配器'
exit()
objNicConfig = colNicConfigs[0]
if connect_and_test(objNicConfig, IPV4_CAOZHU):
exit()
else:
connect_and_test(objNicConfig, IPV4_25)
if __name__ == '__main__':
main()