【问题标题】:How to get Network Interface Card names in Python?如何在 Python 中获取网络接口卡名称?
【发布时间】:2011-04-19 17:17:40
【问题描述】:

我是 python 编程的新手,所以请耐心等待。

有没有办法获取机器等网卡的名称。eth0,lo?如果有,你是怎么做的?

我已经研究过,但到目前为止我只找到了获取 IP 地址和 MAC 地址的代码,例如

import socket
socket.gethostbyname(socket.gethostname())

非常感谢有关代码的建议。谢谢!

【问题讨论】:

    标签: python networking


    【解决方案1】:

    在 Linux 上,您可以通过

    列出 /sys/class/net/ 中的链接
    os.listdir('/sys/class/net/')
    

    不确定这是否适用于所有发行版。

    【讨论】:

      【解决方案2】:

      我曾经这样做过的一个很棒的 Python 库是 psutil。它可以在 Linux、Windows 和 OSX 等平台上使用,支持 Python 2.6 到 3.6。

      Psutil 提供了net_if_addrs() 函数,它返回一个字典,其中键是 NIC 名称,值是分配给 NIC 的每个地址的命名元组列表,其中包括地址族、NIC 地址、网络掩码、广播地址和目的地地址。

      一个使用 net_if_addrs() 的简单示例,它将打印一个 Python 网卡名称列表:

      import psutil
      
      addrs = psutil.net_if_addrs()
      print(addrs.keys())
      

      【讨论】:

      • 这是最好的答案。可在 Win/Linux/Mac 上运行,并且是一个有据可查的库,可用于许多其他操作系统自省。
      【解决方案3】:

      由于当我搜索此信息时会在 Google 中弹出此答案,我想我应该添加我的技术来获取可用接口(以及 IP 地址)。非常棒的模块netifaces 以可移植的方式处理了这一点。

      【讨论】:

      • 很好 - 它甚至在标准库中。实际问题的直接答案是:import netifaces; if_list = netifaces.interfaces()
      • @bitinerant 这不在标准库中。必须使用pip 安装它才能可用。
      • @winsome - 我的错,对不起。 Python 3包默认安装在Ubuntu上,至少18.04桌面(ubuntu-minimal依赖nplan依赖netplan.io依赖python3-netifaces)。
      • 在 Windows 上,此库将 GUID 作为网络名称返回
      【解决方案4】:

      socket Python 中的模块 >= 3.3:

      import socket
      
      # Return a list of network interface information
      socket.if_nameindex()
      

      https://docs.python.org/3/library/socket.html#socket.if_nameindex

      【讨论】:

      • 我要在这里添加一条评论,Windows 支持是在 3.8 中添加的,而不是 3.3。 3.3 仅支持 Linux。
      【解决方案5】:

      我认为标准库中没有任何东西可以查询这些名称。

      如果我在 Linux 系统上需要这些名称,我会解析 ifconfig 的输出或 /proc/net/dev 的内容。看看这个blog entry 是否有类似的问题。

      【讨论】:

      • windows 呢?也有这样的方法吗?
      • Windows 不是我的强项。或许ipconfig /all提供的一些资料适合?
      • 在 Python >= 3.3 中有一个。答案链接:stackoverflow.com/a/58191277/650885
      【解决方案6】:

      为了补充@Kristian Evensen 提到的内容,这是我用于解决我遇到的问题的内容。 如果您只想获取接口列表,请使用:

      interface_list = netifaces.interfaces()
      

      如果你想要一个特定的接口,但不知道最后的数字是什么(即:eth0),请使用:

      interface_list = netifaces.interfaces()
      interface = filter(lambda x: 'eth' in x,interface_list)
      

      【讨论】:

      • @jonas 我以 eth 为例。他们可以使用 lo 代替 eth。我相信我给出的答案足以满足 OP 的要求。不确定是否值得投反对票。
      • 这根本不能回答问题:get the names of the NIC cards in the machine。您根本不知道接口名称或前缀。您应该尽可能灵活地编写代码。
      • @jonas 第一行获取这些名称。
      【解决方案7】:

      使用python的ctypes可以调用C库函数getifaddrs

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      
      from ctypes import *
      
      class Sockaddr(Structure):
          _fields_ = [('sa_family', c_ushort), ('sa_data', c_char * 14)]
      
      class Ifa_Ifu(Union):
          _fields_ = [('ifu_broadaddr', POINTER(Sockaddr)),
                      ('ifu_dstaddr', POINTER(Sockaddr))]
      
      class Ifaddrs(Structure):
          pass
      
      Ifaddrs._fields_ = [('ifa_next', POINTER(Ifaddrs)), ('ifa_name', c_char_p),
                          ('ifa_flags', c_uint), ('ifa_addr', POINTER(Sockaddr)),
                          ('ifa_netmask', POINTER(Sockaddr)), ('ifa_ifu', Ifa_Ifu),
                          ('ifa_data', c_void_p)]
      
      
      def get_interfaces():
          libc = CDLL('libc.so.6')
          libc.getifaddrs.restype = c_int
          ifaddr_p = pointer(Ifaddrs())
          ret = libc.getifaddrs(pointer((ifaddr_p)))
          interfaces = set()
          head = ifaddr_p
          while ifaddr_p:
              interfaces.add(ifaddr_p.contents.ifa_name)
              ifaddr_p = ifaddr_p.contents.ifa_next
          libc.freeifaddrs(head) 
          return interfaces
      
      if __name__ == "__main__":
          print(get_interfaces())
      

      请注意,虽然此方法不可移植。

      【讨论】:

        【解决方案8】:

        就像 David Breuer 说的,在 Linux 上你可以只列出目录“/sys/class/net”。 (它至少适用于 Fedora)。如果您需要有关某些接口的详细信息,可以在接口的目录中导航以获取更多信息。

        def getAllInterfaces():
            return os.listdir('/sys/class/net/')
        

        【讨论】:

          【解决方案9】:

          有一个 python 包 get-nic 提供 NIC 状态、up\down、ip addr、mac addr 等

          
          pip install get-nic
          
          from get_nic import getnic
          
          getnic.interfaces()
          
          Output: ["eth0", "wlo1"]
          
          interfaces = getnic.interfaces()
          getnic.ipaddr(interfaces)
          
          Output: 
          {'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}}
          

          更多信息请参考 GitHub 页面:https://github.com/tech-novic/get-nic-details

          【讨论】:

          • 目前仅支持 Linux 操作系统。
          猜你喜欢
          • 2011-06-15
          • 1970-01-01
          • 1970-01-01
          • 2018-09-12
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          • 2013-06-21
          • 1970-01-01
          相关资源
          最近更新 更多