用Python修改本机适配器信息
主要参考来自【用Python干实事(一)自动修改Windows的IP、网关和DNS设置】。
使用_winreg模块来操作注册表实现相关信息的修改,它是python的内置模块。也可以通过Win32 Extension For Python的wmi模块来实现.
主要用到函数如下:
1.读取注册表
_winreg.OpenKey(key,sub_key,res=0,sam=KEY_READ)
2.枚举当前打开Key的SubKey
_winreg.EnumKey(key, index)
3.查询当前Key的Value和Data
_winreg.QueryValueEx(key, value_name)
4.设置当前key,type下的Value_name的值为value
_winreg.SetValueEx(key, value_name, reserved, type, value)
5.关闭按当前key
_winreg.CloseKey(hkey)
后面输入IP使用正则表达式来进行格式的判断,正则表达式来自【判断IP与MAC地址的正则表达式!!】,运行涉及到修改注册表需要管理员权限。
完整的源代码如下:
1 #-*- encoding:utf-8 -*- 2 import _winreg, os, sys, re 3 from ctypes import * 4 5 #更改系统默认编码 6 reload(sys) 7 sys.setdefaultencoding('utf8') 8 9 NetDescList = [] 10 netCfgInstanceIDList = [] 11 mac_key = r'SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}' 12 13 #正则检验输入IP地址是否合法 14 def ipFormatChk(ip_str): 15 pattern = r"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" 16 if re.match(pattern, ip_str): 17 return True 18 else: 19 return False 20 21 #从注册表读取相关适配器信息 22 def ReadNetworkInfo(): 23 hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, mac_key) 24 keyInfo = _winreg.QueryInfoKey(hkey) 25 #遍历当前Key的子键 26 for index in range(keyInfo[0]): 27 hSubkeyName = _winreg.EnumKey(hkey, index) 28 try: 29 hSubKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, mac_key+'\\'+hSubkeyName) 30 hNdiInfKey = _winreg.OpenKey(hSubKey, r'Ndi\Interfaces') 31 lowerRange = _winreg.QueryValueEx(hNdiInfKey, 'LowerRange') 32 #找到以太网 33 if lowerRange[0] == 'ethernet': 34 value, type = _winreg.QueryValueEx(hSubKey, 'DriverDesc') 35 NetDescList.append(value) 36 netCfgInstanceIDList.append(_winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]) 37 _winreg.CloseKey(hNdiInfKey) 38 _winreg.CloseKey(hSubKey) 39 except : 40 pass 41 _winreg.CloseKey(hkey) 42 43 #修改相关网络信息 44 def ChangeNetWorkInfo(): 45 if len(netCfgInstanceIDList) == 0: 46 print 'Cannot Find Net Info' 47 return 48 ok = False 49 while not ok: 50 51 for index in range(len(NetDescList)): 52 print '-----'+str(index)+'. '+NetDescList[index]+'-----' 53 54 #选择需要修改的网卡 55 ch = raw_input('Please Select: ') 56 if not ch.isdigit() or int(ch) >= len(NetDescList) or int(ch) < 0: 57 print 'Select Error!\n' 58 continue 59 60 KeyName = r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces'+'\\'+str(netCfgInstanceIDList[int(ch)]) 61 #这里需要管理员权限才可以 62 key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, KeyName, 0, _winreg.KEY_ALL_ACCESS) 63 64 ipAddressList = [] 65 subnetMaskList = [] 66 gateWayList = [] 67 dnsServerList = [] 68 69 while True: 70 ipAddress = raw_input('IP Address: ') 71 if ipFormatChk(ipAddress): 72 ipAddressList.append(ipAddress) 73 break; 74 else: 75 print 'Input Format Error' 76 77 while True: 78 subnetMask = raw_input('Subnet Mask: ') 79 if ipFormatChk(subnetMask): 80 subnetMaskList.append(subnetMask) 81 break; 82 else: 83 print 'Input Format Error' 84 85 while True: 86 gateWay = raw_input('GateWay: ') 87 if ipFormatChk(gateWay): 88 gateWayList.append(gateWay) 89 break; 90 else: 91 print 'Input Format Error' 92 93 while True: 94 dnsServer = raw_input('DNS Server: ') 95 if ipFormatChk(dnsServer): 96 dnsServerList.append(dnsServer) 97 break; 98 else: 99 print 'Input Format Error' 100 101 while True: 102 dnsServerBak = raw_input('Standby DNS Server: ') 103 if ipFormatChk(dnsServerBak) or dnsServerBak == '': 104 if dnsServerBak != '': 105 dnsServerList.append(dnsServerBak) 106 break; 107 else: 108 print 'Input Format Error' 109 try: 110 _winreg.SetValueEx(key, 'IPAddress', None, _winreg.REG_MULTI_SZ, ipAddressList) 111 _winreg.SetValueEx(key, 'SubnetMask', None, _winreg.REG_MULTI_SZ, subnetMaskList) 112 _winreg.SetValueEx(key, 'DefaultGateway', None, _winreg.REG_MULTI_SZ, gateWayList) 113 _winreg.SetValueEx(key, 'NameServer', None, _winreg.REG_SZ, ','.join(dnsServerList)) 114 except: 115 print 'Set Network Info Error' 116 exit() 117 _winreg.CloseKey(key) 118 119 # 调用DhcpNotifyConfigChange函数通知IP被修改 120 DhcpNotifyConfigChange = windll.dhcpcsvc.DhcpNotifyConfigChange 121 inet_addr = windll.Ws2_32.inet_addr 122 # DhcpNotifyConfigChange 函数参数列表: 123 # LPWSTR lpwszServerName, 本地机器为None 124 # LPWSTR lpwszAdapterName, 网络适配器名称 125 # BOOL bNewIpAddress, True表示修改IP 126 # DWORD dwIpIndex, 表示修改第几个IP, 从0开始 127 # DWORD dwIpAddress, 修改后的IP地址 128 # DWORD dwSubNetMask, 修改后的子码掩码 129 # int nDhcpAction 对DHCP的操作, 0 - 不修改, 1 - 启用, 2 - 禁用 130 DhcpNotifyConfigChange(None, \ 131 netCfgInstanceIDList[int(ch)], \ 132 True, \ 133 0, \ 134 inet_addr(ipAddressList[0]), \ 135 inet_addr(subnetMaskList[0]), \ 136 0) 137 ok = True 138 139 if __name__ == '__main__': 140 try: 141 ReadNetworkInfo() 142 ChangeNetWorkInfo() 143 print 'Set Network Info OK' 144 except: 145 print 'Require Administrator Permission'
参考来源:
作者:
Tiny656
出处:http://www.cnblogs.com/tiny656
欢迎交流讨论. 236798656 [at] qq.com