您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)怎么在python中修改本地網(wǎng)絡(luò)配置,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
# -*- coding: utf-8 -*- import os import random import re from time import sleep from wmi import WMI #隨機(jī)修改指定ip段的本機(jī)ip class updateIP: def __init__(self): self.wmiService = WMI() #獲取到本地有網(wǎng)卡信息 self.colNicConfigs = self.wmiService.Win32_NetworkAdapterConfiguration(IPEnabled = True) #print self.colNicConfigs[0] def getAdapter(self): flag = 0 #遍歷所有網(wǎng)卡,找到要修改的那個,這里我是用原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 ''' #隨機(jī)選擇了ip的第二段 ip2 = random.choice(['216', '217']) ip3 = random.randint(1, 254) #隨機(jī)生成第三段和第二段的值 ip4 = random.randint(1, 254) newIP = '10.%s.%s.%s' % (ip2, ip3, ip4) arrIPAddresses = [newIP] #設(shè)置新的ip arrSubnetMasks = ['255.248.0.0'] #子網(wǎng)掩碼 arrDefaultGateways = ['10.223.255.254'] #網(wǎng)關(guān) arrGatewayCostMetrics = [1] #這里要設(shè)置成1,代表非自動選擇 arrDNSServers = ['211.137.191.26'] #dns服務(wù)器 #開始執(zhí)行修改ip、子網(wǎng)掩碼、網(wǎng)關(guān) ipRes = adapter.EnableStatic(IPAddress = arrIPAddresses, SubnetMask = arrSubnetMasks) if ipRes[0] == 0: print u'\ttip:設(shè)置IP成功' print u'\t當(dāng)前ip:%s' % newIP else: if ipRes[0] == 1: print u'\ttip:設(shè)置IP成功,需要重啟計算機(jī)!' else: print u'\ttip:修改IP失敗: IP設(shè)置發(fā)生錯誤' return False #開始執(zhí)行修改dns wayRes=adapter.SetGateways(DefaultIPGateway = arrDefaultGateways, GatewayCostMetric=arrGatewayCostMetrics) if wayRes[0] == 0: print u'\ttip:設(shè)置網(wǎng)關(guān)成功' else: print u'\ttip:修改網(wǎng)關(guān)失敗: 網(wǎng)關(guān)設(shè)置發(fā)生錯誤' return False dnsRes = adapter.SetDNSServerSearchOrder(DNSServerSearchOrder=arrDNSServers) if dnsRes[0] == 0: print u'\ttip:設(shè)置DNS成功,等待3秒刷新緩存' sleep(3) #刷新DNS緩存使DNS生效 os.system('ipconfig /flushdns') else: print u'\ttip:修改DNS失敗: DNS設(shè)置發(fā)生錯誤' return False ''' //ping某ip看是否可以通 def pingIP(self, ip): res = os.popen('ping -n 2 -w 1 %s' % ip).read() #內(nèi)容返回到res res = res.decode('gbk') if u'請求超時' in res: #注意亂碼編碼問題 return False else: return True ''' if __name__ == '__main__': update = updateIP() update.runSet() input()
以上就是怎么在python中修改本地網(wǎng)絡(luò)配置,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。