python无法使用物理网卡_Python 实现监控所有物理网卡状态

项目中有监控网卡的需求,但是一般的方法都需要指定某个网卡,然后返回网卡状态,另外如何从所有网卡中过滤出物理网卡也是个问题。

Linux2.6 内核中引入了 sysfs 文件系统。sysfs 文件系统整理的设备驱动的相关文件节点,被视为 dev 文件系统的替代者。同时也拥有类似 proc 文件系统一样查看系统相关信息的功能。最主要的作用是 sysfs 把连接在系统上的设备和总线组织成分级的文件,使其从用户空间可以访问或配置。

sysfs 被加载在 /sys/ 目录下,如 /sys/class/net 目录下包含了所有网络接口,我们这里就是从该目录获取到所有网卡的列表。

但是如何过滤掉虚拟网卡,只获取到物理网卡的列表呢?

这里我们又用到了 /sys/devices/virtual/net 目录,这里又所有的虚拟网卡列表,这样我们就有办法获取到物理网卡列表了。然后再使用 ethtool 命令获取网卡状态即可。

import commands,sys

# get all virtual nic

return_code, output = commands.getstatusoutput("ls /sys/devices/virtual/net")

vnic_list = output.split('\n')

# get all nic, exclude the 'bonding_masters'

return_code, output = commands.getstatusoutput("ls /sys/class/net|grep -v 'bonding_masters'")

nic_list = output.split('\n')

# get all physical nic

#pnic_list = [p_nic for p_nic in nic_list if p_nic not in vnic_list]

pnic_list = list(set(nic_list) - set(vnic_list))

exit_code = 0

exit_list = []

# use ethtool to detect the pnic link status

for pnic in pnic_list:

return_code, output = commands.getstatusoutput("ethtool " + pnic + " |grep detected")

if "no" in output:

exit_list.append(pnic)

exit_code = 2

if exit_code == 0:

print("OK! all inteface is up.")

else:

print("CRITICAL: interface " + str(exit_list) + " is down")

sys.exit(exit_code)

如果觉得有用,欢迎关注我的微信,有问题可以直接交流:

wechat-qcode.jpg

你的关注是对我最大的鼓励!

参考:

你可能感兴趣的:(python无法使用物理网卡)