如何使用python获取本地网卡的正确MAC/以太网id?Google/stackoverflow上的大部分文章都建议解析ipconfig /all (windows)和ifconfig (Linux)的结果。在windows (2x/xp/7)上,'ipconfig /all‘工作正常,但这是一种安全的方法吗?我是linux的新手,我不知道'ifconfig‘是否是获取MAC/以太网id的标准方法。
我必须在python应用程序中实现一个基于本地MAC/以太网id的许可证检查方法。
当您安装了VPN或虚拟化应用程序(如VirtualBox )时,有一种特殊情况。在这种情况下,您将获得多个MAC/以太网In。如果我必须使用解析方法,这将不会是一个问题,但我不确定。
干杯
Prashant
发布于 2010-11-24 01:20:11
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
是一个跨平台的函数,它将为您返回答案。
发布于 2010-11-24 04:03:34
在linux上,您可以通过sysfs访问硬件信息。
>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed
这样就避免了向ifconfig输出和解析输出所带来的复杂性。
发布于 2010-11-24 02:12:31
我使用了基于套接字的解决方案,在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
https://stackoverflow.com/questions/4258822
复制相似问题