本文主要说一下怎么使用Python来修改本地的ip和dns等,因为有本地的ip和dns都是随机获取的,有些时候不是很方便,需要修改,我就稍微的封装了一下,但是随机ip和网关、子网掩码等我都没有设置为参数,因为经常用也懒得改了,可以自己去修改一下。

测试的时候,在win8.1上面需要用管理员身份才能执行,win7似乎是不需要管理员身份的。

使用的Python库是WMI,这个是默认安装了的。如果没有去网上下载即可。

该说的都在注释里,就直接上代码了。

# -*- coding: utf-8 -*-
import os
import random
import re
from time import sleep
from wmi import WMI
#随机修改指定ip段的本机ip
class updateIP:
def __init__(self):
self.wmiService = WMI()
#获取到本地有网卡信息
self.colNicConfigs = self.wmiService.Win32_NetworkAdapterConfiguration(IPEnabled = True)
#print self.colNicConfigs[0]
def getAdapter(self):
flag = 0
#遍历所有网卡,找到要修改的那个,这里我是用原ip的第一段正则出来的
for obj in self.colNicConfigs:
ip = re.findall("10.\d+.\d+.\d+", obj.IPAddress[0])
if len(ip) > 0:
return flag
else:
flag = flag+1
def runSet(self):
adapter = self.colNicConfigs[self.getAdapter()]
'''
#检测ip是否在线,不可用,需登录
while True:
ip2 = random.choice(['216', '217'])
ip3 = random.randint(1, 254)
ip4 = random.randint(1, 254)
newIP = '10.%s.%s.%s' % (ip2, ip3, ip4)
if self.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)
if ipRes[0] == 0:
print u'\ttip:设置IP成功'
print u'\t当前ip:%s' % newIP
else:
if ipRes[0] == 1:
print u'\ttip:设置IP成功,需要重启计算机!'
else:
print u'\ttip:修改IP失败: IP设置发生错误'
return False
#开始执行修改dns
wayRes=adapter.SetGateways(DefaultIPGateway = arrDefaultGateways, GatewayCostMetric=arrGatewayCostMetrics)
if wayRes[0] == 0:
print u'\ttip:设置网关成功'
else:
print u'\ttip:修改网关失败: 网关设置发生错误'
return False
dnsRes = adapter.SetDNSServerSearchOrder(DNSServerSearchOrder=arrDNSServers)
if dnsRes[0] == 0:
print u'\ttip:设置DNS成功,等待3秒刷新缓存'
sleep(3)
#刷新DNS缓存使DNS生效
os.system('ipconfig /flushdns')
else:
print u'\ttip:修改DNS失败: DNS设置发生错误'
return False
'''
//ping某ip看是否可以通
def pingIP(self, ip):
res = os.popen('ping -n 2 -w 1 %s' % ip).read() #内容返回到res
res = res.decode('gbk')
if u'请求超时' in res: #注意乱码编码问题
return False
else:
return True
'''
if __name__ == '__main__':
update = updateIP()
update.runSet()
input()

以上这篇python 修改本地网络配置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考。