Python networking : 找到相应接口的 MAC 地址

Python networking : find MAC address for corresponding interfaces

我从 pmav99 找到了一个脚本。非常感谢他。

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == family:
                yield (interface, snic.address, snic.netmask)

ipv4s = list(get_ip_addresses(socket.AF_INET))

print ipv4s

结果是:

[('Local Area Connection* 2', '169.254.189.147', '255.255.0.0'), ('Ethernet', '192.168.18.34', '255.255.255.0'), ('Wi-Fi', '192.168.1.102', '255.255.255.0'), ('Loopback Pseudo-Interface 1', '127.0.0.1', '255.0.0.0')]

但是在psutil的net_if_addrs()中,它也提供了每个接口的mac地址。那么如何将 mac 地址添加到列表中呢? MAC 地址的键名也是 地址。找不到获取方式。

根据 the documentation,MAC 地址由家庭 psutil.AF_LINK 记录。此代码片段将获取接口名称列表以及 MAC 地址。

macs = list(get_ip_addresses(psutil.AF_LINK))
print macs

以下程序将生成从 MAC 地址到 IPV4 地址的映射:

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == family:
                yield (interface, (snic.address, snic.netmask))

ipv4s = dict(get_ip_addresses(socket.AF_INET))
macs = dict(get_ip_addresses(psutil.AF_LINK))
mac2ipv4 = {macs[k][0]: ipv4s[k] for k in set(macs) & set(ipv4s)}

print mac2ipv4

我找到了一种简单的方法来获得我想要的结果

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == -1 :
                mac = snic.address
            if snic.family == 2 :
                yield (interface, snic.address, snic.netmask, mac)

ipv4 = list(get_ip_addresses(socket.AF_INET))

print ipv4

结果如下所示:

[('Local Area Connection* 2', '169.254.189.147', '255.255.0.0', '34-F3-9A-4C-D0-C5'), ('Ethernet', '192.168.18.34', '255.255.255.0', 'C8-5B-76-AC-B7-BC'), ('Wi-Fi', '192.168.1.106', '255.255.255.0', '34-F3-9A-4C-D0-C4'), ('Loopback Pseudo-Interface 1', '127.0.0.1', '255.0.0.0', '00-00-00-00-00-00-00-E0')]

具有相应 ipv4、网络掩码和 mac 地址的连接名称。 希望对其他访客有帮助:).