首页 > 编程语言 >python 修改服务器网卡信息

python 修改服务器网卡信息

时间:2023-04-25 14:24:32浏览次数:33  
标签:return network python ip param 网卡 netmask 服务器 gateway

import os
import re
import netifaces
import subprocess


class NetWorkConfig:

    def __init__(self):
        pass

    @staticmethod
    def check_network_isvalid(ip, netmask, gateway, dns):
        """
        判断用户输入的网络配置是否可用
        :param ip: str,IP地址
        :param netmask: str,子网掩码
        :param gateway: str,网关
        :param dns: str,DNS
        :return: bool,True表示配置可用,False表示配置不可用
        """
        # 判断IP地址是否合法
        if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
            return False

        # 判断子网掩码是否合法
        if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", netmask):
            return False

        # 判断网关是否合法
        if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", gateway):
            return False

        # 判断DNS是否合法
        if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", dns):
            return False

        # 判断网络是否可用
        cmd_ping = f"ping {gateway}"
        try:
            subprocess.check_call(cmd_ping, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            return False

        return True

    @staticmethod
    def get_network_config(physical=False):
        """
        获取网卡配置信息
        :param physical: 是否仅获取物理网卡
        :return: 返回服务器网卡配置
        """
        i_faces = netifaces.interfaces()
        configs = []
        for i in i_faces:
            if physical and not i.startswith("e"):
                continue
            addr_s = netifaces.ifaddresses(i)
            inet = addr_s.get(netifaces.AF_INET)
            if not inet:
                continue
            ip = inet[0].get("addr")
            netmask = inet[0].get("netmask")
            broadcast = inet[0].get("broadcast")
            gateway = netifaces.gateways().get("default", {}).get(netifaces.AF_INET, [])[0]
            dns = netifaces.gateways().get("default", {}).get(netifaces.AF_INET, [])[1]
            configs.append({
                "iface": i,
                "ip": ip,
                "netmask": netmask,
                "broadcast": broadcast,
                "gateway": gateway,
                "dns": dns,
            })
        return configs

    @staticmethod
    def _check_network_config(iface, ip_address, netmask, gateway, dns):
        """
        检查IP地址和子网掩码修改是否生效
        :param iface: 网卡
        :param ip_address: ip地址
        :param netmask: 子网掩码
        :param gateway: 网关
        :param dns: DNS
        :return: 返回配置是否生效
        """
        # 检查ip地址是否生效
        cmd = f"ifconfig {iface} | grep {ip_address}"
        output = subprocess.check_output(cmd, shell=True)
        if ip_address not in output.decode("utf-8"):
            return False

        # 检查子网掩码是否生效
        cmd = f"ifconfig {iface} | grep {netmask}"
        output = subprocess.check_output(cmd, shell=True)
        if netmask not in output.decode("utf-8"):
            return False

        # 检查默认网关是否生效
        cmd = "route"
        output = subprocess.check_output(cmd, shell=True)
        pattern = rf"{gateway}\s.*\s{iface}"
        matches = re.findall(pattern, output.decode("utf-8"), re.MULTILINE)
        if not matches:
            return False

        # 检查DNS是否生效
        with open("/etc/resolv.conf", "r") as f:
            content = f.read()
        if dns not in content:
            return False

        return True

    @staticmethod
    def _write_network_config_to_file(config, mode="w"):
        """
        配置信息写入网卡
        """
        with open("/etc/network/interfaces", mode) as f:
            f.write(config)

    @staticmethod
    def _restart_network():
        """重启网络"""
        os.system("service networking restart")

    @staticmethod
    def _cp_config(cmd=None):
        """
        拷贝配置文件
        :param cmd: backup表示备份 rollback表示回滚
        """
        if cmd == "backup":
            os.system("cp /etc/network/interfaces /etc/network/interfaces.bak")
        if cmd == "rollback":
            os.system("cp /etc/network/interfaces.bak /etc/network/interfaces")

    def set_network_config(self, iface, ip_address, netmask, gateway, dns):
        """
        修改网络配置
        :param iface: 网卡名称
        :param ip_address: IP地址
        :param netmask: 子网掩码
        :param gateway: 默认网关
        :param dns: DNS服务器
        :return: 是否修改成功
        """
        self._cp_config(cmd="backup")

        config = f"""
            auto {iface}
            iface {iface} inet static
            address {ip_address}
            netmask {netmask}
            gateway {gateway}
            dns-nameservers {dns}
        """

        self._write_network_config_to_file(config, "w")
        self._restart_network()
        if self._check_network_config(iface, ip_address, netmask, gateway, dns):
            return True
        else:
            self._cp_config(cmd="rollback")
            self._restart_network()
            return False

 

标签:return,network,python,ip,param,网卡,netmask,服务器,gateway
From: https://www.cnblogs.com/52-qq/p/17352454.html

相关文章

  • python 相关
    python判断文件是否存在os.path.exists(file_path):python多线程p1=threading.Thread(target=down)t1=threading.Thread(target=crawl)print("启动")p1.start()t1.start()print("join")p1.join()t1.join()python多线程与redis控制多线程的数量whileTr......
  • python编程基础
    Python并不是一门新的编程语言,1991年就发行了第一个版本,2010年以后随着大数据和人工智能的兴起,Python又重新焕发出了耀眼的光芒。在2019年12月份世界编程语言排行榜中,Python排名第三,仅次于Java和C语言。Python是一门开源免费的脚本编程语言,它不仅简单易用,而且功能强大......
  • Hyper-V安装centos系统作为本地服务器教程
    下载CentOS镜像以下是镜像下载地址:https://repo.huaweicloud.com/centos/7.9.2009/isos/x86_64/因为要做服务器使用,所以推荐下CentOS-7-x86_64-Minimal-2009.iso版本。启用Hyper-vwindows系统一般没有默认打开hyper-v功能,需要手动开启。如果已开启请跳过该步骤。按下组合......
  • 分享Python采集88个NET电子商务源码,总有一款适合您
    Python采集的88个NET电子商务源码下载链接:百度网盘请输入提取码 提取码:c0gh编辑众筹系统(RaiseDreams众筹梦想)V2.1.6云点滴客户关系管理CRMOA系统V1.02.13云点滴客户解决方案V1.0.0创想商务B2B网站管理系统V3.1冰兔(Btoo)网店系统V6.39ASP.NET4.0电子商城MVC+EF水果市场2......
  • CentOS 服务器部署 DNS 解析服务
    需求在centos云服务器上部署一个dns解析服务,以供windows电脑可以使用这个服务器ip作为网络的dns代理。我的服务器ip为192.168.126.241,我想在我的windows电脑访问abc.baidu.com时解析到ip为110.112.113.111的服务器上,访问www.baidu.com时解析到123.111.111.111的服务器上。尽量模......
  • windows环境下emacs的python简单配置
    首先参考了上一篇《emacs极简配置》,我的想法是打开兼容vim的viper到5级,然后一些基本的字体设定,然后如何执行python文件的一个全过程方法。1、先打开emacs,如果忘了怎么用了,看一下自带的教程,还是中文的,超级方便。2、学完后,键入C-xC-f并按~,这样就会打开默认的配置文件所在的目录......
  • Python之peewee|4-22
    frompeeweeimport*db=MySQLDatabase('my_database',user='xxx',password='P@x',host='xxxxxx',port=3306)classUser(Model):name=CharField()email=CharField()classMeta:......
  • Python语言中__init__与__new__的区别是什么?
    __new__和__init__二者都是Python面向对象语言中的函数,其中__new__比较少用,__init__相对常用,那么两者有什么区别呢?以下是详细的内容:__new__作用:创建对象,并分配内存__init__作用:初始化对象的值注意:1、与java相比,java只有一个构造器。而python__new__方法与__in......
  • python画甘特图
    #-*-coding:utf-8-*-#pipinstallplotly-ihttps://pypi.tuna.tsinghua.edu.cn/simpleimportplotlyaspyimportplotly.figure_factoryasffpyplt=py.offline.plot###test1df=[dict(Task="项目1",Start='2015-02-05',Finish......
  • python编程经验
    1、#在此基础上获取最大长度共同子字符串sub_len=min_lenwhiles1[s1_index+i:s1_index+i+sub_len]==s2[s2_index+j:s2_index+j+sub_len]:sub_len+=1#实际的最大共同子字符串长度sub_len=sub_len-1在比较算法中,上述代码不断循环执行,sub_len递增。即默认......