温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中修改本地网络配置

发布时间:2021-03-16 15:51:34 来源:亿速云 阅读:578 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关怎么在python中修改本地网络配置,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

# -*- 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中修改本地网络配置,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI