You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PyRoute2是否有Psutil等效功能?求获取网卡类ifconfig信息方法

获取PyRoute2中类似ifconfig的网卡信息(含Network Namespaces支持)

Hey there! I totally get the frustration when RTFM doesn’t hand you the exact answer you need—PyRoute2’s documentation can feel a bit scattered when you’re hunting for specific NIC stats like the ones ifconfig spits out. Let’s walk through how to pull all those details you need (link state, Rx/Tx counters, speed/duplex) both inside and outside network namespaces.

1. 用IPDB获取基础链路状态与流量计数器

PyRoute2的IPDB是高层接口,能轻松拿到大部分核心网卡信息,包括链路状态和收发统计数据。这里有个实用的示例:

from pyroute2 import IPDB

# 初始化IPDB(默认针对当前网络命名空间)
with IPDB() as ipdb:
    for if_name, iface in ipdb.interfaces.items():
        print(f"\n=== 网卡: {if_name} ===")
        # 链路状态(UP/DOWN)
        print(f"链路状态: {'UP' if iface['operstate'] == 'UP' else 'DOWN'}")
        # 硬件地址
        print(f"MAC地址: {iface['address']}")
        # Rx/Tx 统计计数器
        stats = iface['stats']
        print(f"接收字节数: {stats['rx_bytes']} | 接收数据包数: {stats['rx_packets']}")
        print(f"接收错误数: {stats['rx_errors']} | 接收丢弃数: {stats['rx_dropped']}")
        print(f"发送字节数: {stats['tx_bytes']} | 发送数据包数: {stats['tx_packets']}")
        print(f"发送错误数: {stats['tx_errors']} | 发送丢弃数: {stats['tx_dropped']}")

2. 用ETHTool获取速率与双工信息

ifconfig里的速率、双工这类细节需要调用ethtool接口,PyRoute2的ETHTool类专门干这个:

from pyroute2 import ETHTool

with ETHTool() as ethtool:
    # 替换成你要查询的网卡名,比如eth0、ens33
    nic_name = "eth0"
    link_info = ethtool.get_link(nic_name)
    
    print(f"\n=== {nic_name} 链路详情 ===")
    print(f"速率: {link_info['speed']} Mbps")
    print(f"双工模式: {'全双工' if link_info['duplex'] == 1 else '半双工'}")
    print(f"自动协商: {'开启' if link_info['autoneg'] == 1 else '关闭'}")

3. 在Network Namespaces中获取信息

PyRoute2对netns的支持很友好,你可以两种方式查询其他命名空间的网卡信息:

方式一:进入目标NetNS后查询

直接切换到目标命名空间,再初始化IPDB/ETHTool:

from pyroute2 import NetNS, IPDB, ETHTool

# 替换成你的NetNS名称,比如'my_test_ns'
target_ns = "my_test_ns"

with NetNS(target_ns) as ns:
    # 在NetNS内初始化IPDB
    with IPDB(nl=ns) as ipdb:
        print(f"\n=== 命名空间 {target_ns} 内的网卡 ===")
        for if_name, iface in ipdb.interfaces.items():
            print(f"{if_name}: {'UP' if iface['operstate'] == 'UP' else 'DOWN'}")
    
    # 在NetNS内查询速率双工
    with ETHTool(nl=ns) as ethtool:
        link_info = ethtool.get_link("eth0")
        print(f"eth0 速率: {link_info['speed']} Mbps")

方式二:不进入NetNS,直接指定后端查询

如果你不想切换命名空间,也可以把NetNS实例作为后端传递给IPDB/ETHTool:

from pyroute2 import NetNS, IPDB

target_ns = "my_test_ns"
ns = NetNS(target_ns)

with IPDB(nl=ns) as ipdb:
    print(f"\n=== 命名空间 {target_ns} 网卡统计 ===")
    for if_name, iface in ipdb.interfaces.items():
        print(f"{if_name} 接收字节: {iface['stats']['rx_bytes']}")

ns.close()  # 记得关闭NetNS连接

一些注意事项

  • 权限问题:获取部分网卡统计信息需要root权限,记得用sudo运行脚本。
  • 虚拟接口限制:像veth、docker0这类虚拟接口可能没有速率/双工数据,因为它们是软件虚拟的链路。
  • 内核版本差异:ETHTool返回的字段可能随内核版本略有不同,你可以直接print(link_info)查看所有可用字段。

内容的提问来源于stack exchange,提问作者bli

火山引擎 最新活动