主要参考来自【用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'

参考来源:

python利用_winreg模块制作MAC地址修改工具

用Python干实事(一)自动修改Windows的IP、网关和DNS设置

判断IP与MAC地址的正则表达式!!

最新文章

  1. JS高程5.引用类型(4)Array类型的各类方法
  2. Servlet和JSP学习指导与实践(二):Session追踪
  3. 营业额统计(SBT)
  4. win7升级为Win10 10586版本,出现应用商店打不开的解决办法
  5. css position, display, float 内联元素、块级元素
  6. 二、JavaScript语言--JS基础--JavaScript进阶篇--事件响应
  7. STL algorithm算法minmax,minmax_element(36)
  8. CentOS7--iptables的配置
  9. 20164310Exp2后门原理与实践
  10. mongodb 创建更新语法
  11. com.borland.jbcl.layout.*;(XYLayout)
  12. mysqlcheck与myisamchk的区别
  13. Arduino+Avr libc制作Badusb原理及示例讲解
  14. IE与非IE window.onload调用
  15. 动态产生select option列表
  16. 正确理解web交互中的cookie与session
  17. 使用Xcode自带的单元测试
  18. Maven环境变量配置和在Eclipse中的配置
  19. 爬虫必备—requests
  20. 庆祝团队合著的《自主实现SDN虚拟网络与企业私有云》终于得以出版 --- 本人负责分布式存储部分的编写

热门文章

  1. JVM故障处理工具,使用总结
  2. 日常采坑:.NET Core SDK版本问题
  3. 原生工程接入Flutter实现混编
  4. python中json模块的使用
  5. python工业互联网应用实战3—Django Admin列表
  6. jQuery 留言表单验证
  7. vue.esm.js?efeb:628 [Vue warn]: Invalid prop: type check failed for prop &quot;defaultActive&quot;. Expected String with value &quot;0&quot;, got Number with value 0.
  8. Bitter.Core系列九:Bitter ORM NETCORE ORM 全网最粗暴简单易用高性能的 NETCore 之 WITH 子句支持
  9. 浅谈linux IO csy 360技术 2021-01-18
  10. (004)每日SQL学习:物化视图之二