使用Python获取以太网ID
如何用Python获取本地网卡的正确MAC地址或以太网ID?
在谷歌或StackOverflow上,大多数文章建议解析“ipconfig /all”(在Windows上)和“ifconfig”(在Linux上)的结果。
在Windows系统(比如2x、XP、7)中,“ipconfig /all”运行得很好,但这算不算一种可靠的方法呢?
我对Linux还不太熟悉,不知道“ifconfig”是否是获取MAC地址或以太网ID的标准方法。
我需要在一个Python应用中实现一个基于本地MAC地址或以太网ID的许可证检查方法。
如果你安装了VPN或虚拟化软件,比如VirtualBox,就会出现一个特殊情况。在这种情况下,你会得到多个MAC地址或以太网ID。如果我需要使用解析的方法,这不会成为问题,但我不太确定。
谢谢!
Prashant
3 个回答
2
我使用了一种基于套接字的解决方案,这在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")
4
在Linux系统中,你可以通过sysfs来获取硬件信息。
>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed
这样做可以避免使用ifconfig命令时遇到的复杂情况,也不用去分析它输出的内容。
6
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
这是一个跨平台的功能,可以为你返回答案。