我需要一个跨平台的方法来确定运行时计算机的 MAC 地址。对于 windows,可以使用‘ wmi’模块,而在 Linux 下我能找到的唯一方法是运行 ifconfig 并在其输出上运行 regex。我不喜欢使用只能在一个操作系统上运行的软件包,而且解析另一个程序的输出似乎不太合适,更不用说容易出错了。
有人知道一种跨平台的方法(windows 和 linux)来获取 MAC 地址吗?如果没有,还有人知道比我上面列出的方法更优雅的方法吗?
还有一点需要注意的是,uuid.getnode()可以通过返回一个随机的48位数字来伪造 MAC 地址,这个数字可能不是您所期望的。此外,没有明确的迹象表明 MAC 地址是伪造的,但是您可以通过两次调用 getnode()来检测它,看看结果是否有所不同。如果两个调用返回相同的值,那么就得到了 MAC 地址,否则就得到了一个伪造的地址。
>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
当您知道需要 MAC 的 iface 的 IP 时,这将使用 netifaces(可在 PyPI 中获得)完成以下工作:
import netifaces as nif
def mac_for_ip(ip):
'Returns a list of MACs for interfaces that have given IP, returns None if not found'
for i in nif.interfaces():
addrs = nif.ifaddresses(i)
try:
if_mac = addrs[nif.AF_LINK][0]['addr']
if_ip = addrs[nif.AF_INET][0]['addr']
except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
if_mac = if_ip = None
if if_ip == ip:
return if_mac
return None