python 修改本地网络配置的方法
本文主要说一下怎么使用Python来修改本地的ip和dns等,因为有本地的ip和dns都是随机获取的,有些时候不是很方便,需要修改,我就稍微的封装了一下,但是随机ip和网关、子网掩码等我都没有设置为参数,因为经常用也懒得改了,可以自己去修改一下。
测试的时候,在win8.1上面需要用管理员身份才能执行,win7似乎是不需要管理员身份的。
使用的Python库是WMI,这个是默认安装了的。如果没有去网上下载即可。
该说的都在注释里,就直接上代码了。
#-*-coding:utf-8-*-
importos
importrandom
importre
fromtimeimportsleep
fromwmiimportWMI
#随机修改指定ip段的本机ip
classupdateIP:
def__init__(self):
self.wmiService=WMI()
#获取到本地有网卡信息
self.colNicConfigs=self.wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
#printself.colNicConfigs[0]
defgetAdapter(self):
flag=0
#遍历所有网卡,找到要修改的那个,这里我是用原ip的第一段正则出来的
forobjinself.colNicConfigs:
ip=re.findall("10.\d+.\d+.\d+",obj.IPAddress[0])
iflen(ip)>0:
returnflag
else:
flag=flag+1
defrunSet(self):
adapter=self.colNicConfigs[self.getAdapter()]
'''
#检测ip是否在线,不可用,需登录
whileTrue:
ip2=random.choice(['216','217'])
ip3=random.randint(1,254)
ip4=random.randint(1,254)
newIP='10.%s.%s.%s'%(ip2,ip3,ip4)
ifself.pingIP(newIP):
break
'''
#随机选择了ip的第二段
ip2=random.choice(['216','217'])
ip3=random.randint(1,254)#随机生成第三段和第二段的值
ip4=random.randint(1,254)
newIP='10.%s.%s.%s'%(ip2,ip3,ip4)
arrIPAddresses=[newIP]#设置新的ip
arrSubnetMasks=['255.248.0.0']#子网掩码
arrDefaultGateways=['10.223.255.254']#网关
arrGatewayCostMetrics=[1]#这里要设置成1,代表非自动选择
arrDNSServers=['211.137.191.26']#dns服务器
#开始执行修改ip、子网掩码、网关
ipRes=adapter.EnableStatic(IPAddress=arrIPAddresses,SubnetMask=arrSubnetMasks)
ifipRes[0]==0:
printu'\ttip:设置IP成功'
printu'\t当前ip:%s'%newIP
else:
ifipRes[0]==1:
printu'\ttip:设置IP成功,需要重启计算机!'
else:
printu'\ttip:修改IP失败:IP设置发生错误'
returnFalse
#开始执行修改dns
wayRes=adapter.SetGateways(DefaultIPGateway=arrDefaultGateways,GatewayCostMetric=arrGatewayCostMetrics)
ifwayRes[0]==0:
printu'\ttip:设置网关成功'
else:
printu'\ttip:修改网关失败:网关设置发生错误'
returnFalse
dnsRes=adapter.SetDNSServerSearchOrder(DNSServerSearchOrder=arrDNSServers)
ifdnsRes[0]==0:
printu'\ttip:设置DNS成功,等待3秒刷新缓存'
sleep(3)
#刷新DNS缓存使DNS生效
os.system('ipconfig/flushdns')
else:
printu'\ttip:修改DNS失败:DNS设置发生错误'
returnFalse
'''
//ping某ip看是否可以通
defpingIP(self,ip):
res=os.popen('ping-n2-w1%s'%ip).read()#内容返回到res
res=res.decode('gbk')
ifu'请求超时'inres:#注意乱码编码问题
returnFalse
else:
returnTrue
'''
if__name__=='__main__':
update=updateIP()
update.runSet()
input()
以上这篇python修改本地网络配置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。