python-netifaces模块

netifaces

1. introduction

在Linux系统中,我们可以使用ip addr、ifconfig、route等命令查看系统网络等相关配置。也可以在查询结果中使用正则表达式,管道,awk等处理提取相关信息。

在python中可以使用第三方库netifaces获取有关网络接口及状态的信息,如ip地址,MAC地址等。

2. install

2.1 source install

tar xvzf netifaces-0.10.4.tar.gz

cd netifaces-0.10.4

sudo python setup.py install

2.2 pip install

pip3 install netifaces

3. employ

3.1 获取网络接口名

    @staticmethod
    def get_local_interfaces() -> list:
        """
        description: 获取本机网络接口名
        :return: ['lo', 'enp3s0']
        """

        interfaces = netifaces.interfaces()
        print(interfaces)
        return interfaces

3.2 根据接口名获取网络信息

    @staticmethod
    def get_local_info():
        """
        description: 根据网络接口名获取网络信息
        :return:
        """
        interfaces = netifaces.interfaces()

        for interface in interfaces:
            print(netifaces.ifaddresses(interface))

{

​ 17: [

​ {

​ ‘addr’: ‘4c:cc:6a:19:6b:53’,

​ ‘broadcast’: ‘ff:ff:ff:ff:ff:ff’

​ }

​ ],

​ 2: [

​ {

​ ‘addr’: ‘192.168.7.101’,

​ ‘netmask’: ‘255.255.255.0’,

​ ‘broadcast’: ‘192.168.7.255’

​ }

​ ],

​ 10: [

​ {

​ ‘addr’: ‘fe80::5468:5c8c:57c6:b936%enp3s0’,

​ ‘netmask’: ‘ffff:ffff:ffff:ffff::/64’

​ }

​ ]

}

返回值详解:

  1. 数据类型:字典
  2. 与linux系统执行ifconfig命令输出结果基本一致,就是对应网卡的详细信息。通过这些信息可以得到期望的ipmac等信息。
  3. key值是netifaces.address_families中映射的值,例如17对应的是AF_PACKET信息,2对应的是AF_INET也就是IPV4信息。
  4. 可以通过映射值直接获取信息。

3.3 映射常量值

    @staticmethod
    def get_families():
        print(netifaces.address_families)

3.4 获取路由信息

    @staticmethod
    def get_local_gateway():
        """
        description: 获取路由信息
        :return: {'default': {2: ('192.168.7.254', 'enp3s0')}, 2: [('192.168.7.254', 'enp3s0', True)]}
        """
        netifaces.gateways()

4. example

4.1 get local ip

    @staticmethod
    def get_ip():
        interfaces = netifaces.interfaces()

        for interface in interfaces:
            info = netifaces.ifaddresses(interface)
            local_info = info[netifaces.AF_INET][0]
            local_ip = local_info['addr']
            print(local_ip)

4.2 get local netmask

    @staticmethod
    def get_netmask():
        interfaces = netifaces.interfaces()

        for interface in interfaces:
            info = netifaces.ifaddresses(interface)
            local_info = info[netifaces.AF_INET][0]
            local_netmask = local_info['netmask']
            print(local_netmask)

4.3 get gateway ip

    @staticmethod
    def get_gateway():
        gateway = netifaces.gateways().get(netifaces.AF_INET)
        local_gateway = gateway[0][0]
        print(local_gateway)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值