主要参考来自【用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. 剑指offer-查找数组中重复的数字

    找出数组中重复的数字. 在一个长度为 n 的数组 nums 里的所有数字都在 0-n-1 的范围内.数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次.请找出数组中任意一个重 ...

  2. PMP知识领域

    · 十大知识领域 整合-项目整合管理 识别.定义.组合.统一和协调个项目管理过程组的各种过程和活动而展开的活动与过程. 整合:统一.合并.沟通和简历联系:贯穿项目始终 七个过程组 一.制定项目章程(启 ...

  3. 日常采坑:.NetCore上传大文件

    一..NetCore上传大文件 .NetCore3.1 webapi 本地测试上传时,遇到一个坑,大点的文件直接失败,根本不走控制器方法. 二.大文件上传配置 IFormFile方式,vs IIS E ...

  4. 【Linux】使用 iperf 测试 Linux 服务器带宽

    iperf 简介 iperf 是一个用于测试网络带宽的命令行工具,可以测试服务器的网络吞吐量.目前发现两个很实用的功能: 测试服务器网络吞吐量:如果我们需要知道某台服务器的「最大」网络带宽,那么最好在 ...

  5. Flink源码剖析:Jar包任务提交流程

    Flink基于用户程序生成JobGraph,提交到集群进行分布式部署运行.本篇从源码角度讲解一下Flink Jar包是如何被提交到集群的.(本文源码基于Flink 1.11.3) 1 Flink ru ...

  6. 分布式系统:分布式任务调度xxl-job较深入使用

    目录 系统关键概念介绍 执行器 任务 任务配置项描述 阻塞策略 路由策略 日志问题 客户端日志 服务端日志 框架目前发现的缺点以及存在的问题 xxl-job是一个分布式定时任务调度框架,功能强大,底层 ...

  7. VMware下安装Ubantu 18.04

    一.VIM安装及配置 1.安装VIM sudo apt-get install vim 二.拼音输入法以及搜狗拼音输入法安装 1.安装Fcitx输入框架 sudo apt-get install fc ...

  8. 本地Mac通过堡垒机代理实现跨堡垒机scp问题

    近日,公司在跳板机前架设了堡垒机,以防止ssh攻击,但这带来一个问题,我们平常直接ssh跳板机,可以直接使用scp来上传或下载跳板机数据到本地 架设堡垒之后经常使用的scp工具不好用了 于是本期就来解 ...

  9. uni-app开发经验分享十八:对接第三方h5

    1.uni-app中对接第三方为了防止跳出app使用了webview <template> <view> <web-view :src="url" @ ...

  10. Redis 核心篇:唯快不破的秘密

    天下武功,无坚不摧,唯快不破! 学习一个技术,通常只接触了零散的技术点,没有在脑海里建立一个完整的知识框架和架构体系,没有系统观.这样会很吃力,而且会出现一看好像自己会,过后就忘记,一脸懵逼. 跟着「 ...