简体   繁体   English

如何获取Python中的网卡名称?

[英]How to get Network Interface Card names in Python?

Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo?有没有办法在机器等中获取 NIC 卡的名称。eth0,瞧? If so how do you do it?如果是这样,你是怎么做到的?

I have researched but so far I have only found code to get IP addresses and MAC addresses only such as我已经研究过,但到目前为止我只找到了获取 IP 地址和 MAC 地址的代码,例如

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

Advice on the code would really be appreciated.非常感谢有关代码的建议。

On Linux, you can just list the links in /sys/class/net/ by 在Linux上,您只需列出/ sys / class / net /中的链接即可

os.listdir('/sys/class/net/')

Not sure if this works on all distributions. 不确定这是否适用于所有发行版。

socket module in Python >= 3.3: Python >= 3.3 中的socket模块:

import socket

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

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

A great Python library I have used to do this is psutil . 我曾经用过的一个很棒的Python库就是psutil It can be used on Linux, Windows, and OSX among other platforms and is supported from Python 2.6 to 3.6. 它可以在Linux,Windows和OSX等其他平台上使用,并且受Python 2.6到3.6的支持。

Psutil provides the net_if_addrs() function which returns a dictionary where keys are the NIC names and value is a list of named tuples for each address assigned to the NIC which include the address family, NIC address, netmask, broadcast address, and destination address. Psutil提供net_if_addrs()函数,该函数返回一个字典,其中键是NIC名称,value是分配给NIC的每个地址的命名元组列表,包括地址族,NIC地址,网络掩码,广播地址和目标地址。

A simple example using net_if_addrs() which will print a Python list of the NIC names: 使用net_if_addrs()简单示例将打印NIC名称的Python列表:

import psutil

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

Since this answer pops up in Google when I search for this information, I thought I should add my technique for getting the available interfaces (as well as IP addresses). 由于当我搜索这些信息时,谷歌会弹出这个答案,我想我应该添加我的技术来获取可用的接口(以及IP地址)。 The very nice module netifaces takes care of that, in a portable manner. 非常好的模块netifaces以便携的方式处理这个问题。

I don't think there's anything in the standard library to query these names. 我认为标准库中没有任何东西可以查询这些名称。

If I needed these names on a Linux system I would parse the output of ifconfig or the contents of /proc/net/dev . 如果我在Linux系统上需要这些名称,我会解析ifconfig的输出或/proc/net/dev Look at this blog entry for a similar problem. 查看此博客条目是否存在类似问题。

Using python's ctypes you can make a call to the C library function getifaddrs : 使用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())

Do note though this method is not portable. 请注意,此方法不可移植。

To add to what @Kristian Evensen's mentions, here is what I used for a problem i was having. 为了补充@Kristian Evensen提到的内容,这里是我用来解决问题的原因。 If you are looking to just get a list of the interfaces, use: 如果您只想获得接口列表,请使用:

interface_list = netifaces.interfaces()

If you are wanting a specific interface, but don't know what the number at the end is (ie: eth0), use: 如果您想要一个特定的接口,但不知道最后的数字是什么(即:eth0),请使用:

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

Like David Breuer say, you can just list the directory "/ sys / class / net" on Linux. 就像David Breuer所说,你可以在Linux上列出目录“/ sys / class / net”。 (It works on Fedora at least). (它至少适用于Fedora)。 If you need detailled information about some interface you can navigate on the intefaces's directories for more. 如果您需要有关某些界面的详细信息,可以在界面的目录中导航以获取更多信息。

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

There is a python package get-nic which gives NIC status, up\\down, ip addr, mac addr etc 有一个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'}}

Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details 有关更多信息,请参阅GitHub页面: https//github.com/tech-novic/get-nic-details

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM