通过python修改本地ip
写在前面,
1 对于个人公司需要固定ip,而回家需要用到家里的ip,
2对于公司it人员,每台电脑都需要设置ip,,尤其批量的时候,这个作为it的自己知道
3运维人员,可以通过ip测试哪些ip可以用,哪些不可以用
准备
拥戴wmi库通过pip install wmi安装
代码
由于比较时间紧,没写界面,只能黑窗口操作,侯琼会补上
# -*- coding: utf-8 -*-
import osimport randomimport refrom time import sleepfrom wmi import WMI#随机修改指定ip段的本机ipclass 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()
浙公网安备 33010602011771号