【问题标题】:MAC, ethernet id using pythonMAC,以太网ID使用python
【发布时间】:2011-05-14 14:46:40
【问题描述】:

如何使用 python 获取本地网卡的正确 MAC/以太网 ID? Google/stackoverflow 上的大部分文章都建议解析 ipconfig /all (windows) 和 ifconfig (Linux) 的结果。 在 Windows (2x/xp/7) 上,“ipconfig /all”工作正常,但这是一种故障安全方法吗? 我是 linux 新手,我不知道“ifconfig”是否是获取 MAC/以太网 ID 的标准方法。

我必须在基于本地 MAC/以太网 id 的 python 应用程序中实现许可证检查方法。

当您安装了 VPN 或 VirtualBox 等虚拟化应用程序时,有一种特殊情况。在这种情况下,您将获得多个 MAC/以太网 ID。如果我必须使用解析方法,这不会成为问题,但我不确定。

干杯

普拉尚特

【问题讨论】:

  • "我必须在基于本地 MAC/以太网 id 的 python 应用程序中实现许可证检查方法" - 您知道 MAC 地址很容易伪造,并且在大多数系统上不安全吗?

标签: python ethernet mac-address


【解决方案1】:
import sys
import os

def getMacAddress(): 
    if sys.platform == 'win32': 
        for line in os.popen("ipconfig /all"): 
            if line.lstrip().startswith('Physical Address'): 
                mac = line.split(':')[1].strip().replace('-',':') 
                break 
    else: 
        for line in os.popen("/sbin/ifconfig"): 
            if line.find('Ether') > -1: 
                mac = line.split()[4] 
                break 
    return mac      

是一个跨平台的函数,会为你返回答案。

【讨论】:

  • 我在一篇文章中看到过这个解决方案。我确信这可以在 Windows 上运行,但在 linux 上我不知道“/sbin/ifconfig”是一个标准命令,并且可以独立于您使用的任何发行版运行。
  • ifconfig 将存在于几乎所有 linux 系统上,尽管您说得对,这是一个通常很脆弱的解决方案。欢迎编写系统特定代码.. :-/ (这发生在任何语言中,顺便说一句,不仅仅是 Python)。只需充分抽象这段代码(我会让它更加更加具体,以便您立即了解您未计划使用的平台),然后使用它。
【解决方案2】:

在linux上,可以通过sysfs访问硬件信息。

>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed

这样您就可以避免使用 ifconfig 和解析输出的复杂性。

【讨论】:

  • 除非需要sysfs,这比ifconfig少得多。
  • 是的,但如果你像我一样,并且几乎只为 Linux 开发,这就是你所需要的 :)
【解决方案3】:

我使用了基于套接字的解决方案,在 linux 上运行良好,我相信 windows 也可以

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]

getHwAddr("eth0")

Original Source

【讨论】:

  • 不适用于 Windows:没有 fcntl 模块。还是谢谢。
猜你喜欢
  • 2016-09-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2022-09-30
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多