Python: check whether a network interface is up

前端 未结 6 443
孤城傲影
孤城傲影 2020-12-03 15:52

In Python, is there a way to detect whether a given network interface is up?

In my script, the user specifies a network interface,

6条回答
  •  一向
    一向 (楼主)
    2020-12-03 16:23

    With pyroute2.IPRoute:

    from pyroute2 import IPRoute
    ip = IPRoute()
    state = ip.get_links(ip.link_lookup(ifname='em1'))[0].get_attr('IFLA_OPERSTATE')
    ip.close()
    

    With pyroute2.IPDB:

    from pyroute2 import IPDB
    ip = IPDB()
    state = ip.interfaces.em1.operstate
    ip.release()
    

提交回复
热议问题