主要参考来自【用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地址的正则表达式!!

用Python修改本机适配器信息的更多相关文章

  1. windows下用C++修改本机IP地址

    两种方法 第一种.使用DOS命令(即时生效) 第二种.修改注册表(重启生效) 1.打开SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards ...

  2. python学习之最简单的获取本机ip信息的小程序

    文章是从我的个人博客粘贴过来的,大家可以直接访问我的个人博客哦 http://www.iwangzheng.com 获取本机ip信息的命令ifconfig总是在用,这次拿到pyhton代码里,感觉py ...

  3. [批处理]自动修改本机IP地址

    前言 抱着笔记本经常到处跑的人,今天回宿舍上网,明天去机房上网,后面去办公室上网,每到一个地方,都要更换一次IP网关掩码 如果都是DHCP还好,关键是为了组织为了方便管理这些地方都是使用的静态IP,所 ...

  4. 基于python的堡垒机

    一 堡垒机的架构 堡垒机的核心架构通常如下图所示: 二.堡垒机的一般执行流程 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码) 用户登陆堡垒机,输入堡垒机用户名密码,显示当前用户 ...

  5. Android开发之蓝牙 --修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备

    一. 修改本机蓝牙设备的可见性 二. 扫描周围可用的蓝牙设备 一.  清单文件AdroidManifest.xml: <uses-permission android:name="an ...

  6. 翻译文章“AST 模块:用 Python 修改 Python 代码”---!!注意ironpathyon未实现此功能

    https://github.com/upsuper/blog/commit/0214fdd084c4adf2de2ed9912d644fb59ce13a1c +Title: [翻译] AST 模块: ...

  7. 做一个自动修改本机IP和mac的bat文件

    原文:做一个自动修改本机IP和mac的bat文件 1.ip bat修改理论探讨 前两天我突然萌生了一个念头:能不能做一个小程序来实现自动配置或修改IP和mac,达到一键搞定的目的,这样尤其适合那些带着 ...

  8. Linux修改本机/etc/hosts的hostName

    1.Linux修改本机别名/etc/hosts的hostName后经常不生效解决 Linux修改本机别名/etc/hosts的hostName后经常不生效, 比如我们/etc/hosts的内容如下: ...

  9. python爬虫之User-Agent用户信息

    python爬虫之User-Agent用户信息 爬虫是自动的爬取网站信息,实质上我们也只是一段代码,并不是真正的浏览器用户,加上User-Agent(用户代理,简称UA)信息,只是让我们伪装成一个浏览 ...

随机推荐

  1. Centos 6 下安装 OSSEC-2.8.1 邮件告警 (二)

    Ossec 配置邮件通知 ## 1 安装软件包: yum install -y sendmail mailx cyrus-sasl cyrus-sasl-plain #安装postfix邮件相关的软件 ...

  2. git revert 回退已经push的内容

    如题,在日常的开发过程中,可能有组员不小心一下子吧文件修改,需要进行回退 回退主要涉及到2种命令,一种是git reset 一种是 git revert git reset 会修改git log提交历 ...

  3. 用percona monitoring plugins 监控mysql

    下载:http://www.percona.com/redir/downloads/percona-monitoring-plugins/1.1.1/percona-zabbix-templates- ...

  4. 解决ROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'creat table study_record( id int(11) not null

    之前一直用的好好的,突然就出现了这个错误: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual tha ...

  5. 爬虫学习(三)Chrome浏览器使用

    一.新建隐身窗口 在打开隐身窗口的时候,第一次请求某个网站是没有携带cookie的,和代码请求一个网站一样,不携带cookie.这样就能够尽可能的理解代码请求某个网站的结果:除非数据是通过js加载出来 ...

  6. Pytorch入门——手把手教你MNIST手写数字识别

    MNIST手写数字识别教程 要开始带组内的小朋友了,特意出一个Pytorch教程来指导一下 [!] 这里是实战教程,默认读者已经学会了部分深度学习原理,若有不懂的地方可以先停下来查查资料 目录 MNI ...

  7. python7、8章

    目录 第七章 用户输入和while循环 7.1 函数input()的工作原理 7.1.1 编写清晰的程序 7.1.2 使用int()来获取数值输入 分析: 结果: 7.1.3 求模运算符 7.1.4 ...

  8. Java 8中字符串拼接新姿势:StringJoiner

    介绍 StringJoiner是java.util包中的一个类,用于构造一个由分隔符分隔的字符序列(可选),并且可以从提供的前缀开始并以提供的后缀结尾.虽然这也可以在StringBuilder类的帮助 ...

  9. 数据库 | 001-MySQL梳理系列(一)

    MySQL基本组成 SQL执行流程 Server 层主要包括连接器.查询缓存.分析器.优化器.执行器,包含了MySQL主要的很多核心功能,以及所有的内置函数.存储过程.触发器.视图等,其实就是所有跨存 ...

  10. 转 9 jmeter之检查点

    9 jmeter之检查点   jmeter有类似loadrunner检查点的功能,就是断言中的响应断言. 1.响应断言(对返回文字结果进行相应的匹配)右击请求-->添加-->断言--> ...