通過python修改本地ip


寫在前面,

1 對於個人公司需要固定ip,而回家需要用到家里的ip,

2對於公司it人員,每台電腦都需要設置ip,,尤其批量的時候,這個作為it的自己知道

3運維人員,可以通過ip測試哪些ip可以用,哪些不可以用

准備

擁戴wmi庫通過pip install 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 ()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM