【Python】通过网卡(网桥)名称获取mac地址,针对多网卡情况

一个简单的方法:

>>> import uuid
>>> node = uuid.getnode()
>>> mac = uuid.UUID(int=node)
>>> addr = mac.hex[-12:]
>>> addr


但是对于多网卡呢?下面的可以用:
法一:
>>> import os
>>> mac = os.popen("/sbin/ifconfig | grep 'br0'|awk '{print $5}'").read()
>>> mac
'00:1b:cd:03:10:ac\n'
>>> mac = mac[mac.find(':')+1:mac.find('\n')]
>>> mac
'1b:cd:03:10:ac'
>>> mac = string.replace(mac,":","",4)
'1bcd0310ac'

法二:给出interface字符串形式,如interface = 'eth0'
import fcntl
import struct
import  socket
def get_interface_mac(interface):
    DEVICE_NAME_LEN = 15
    MAC_START = 18
    MAC_END = 24
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,
                       struct.pack('256s', interface[:DEVICE_NAME_LEN]))
    return ''.join(['%02x:' % ord(char)
                    for char in info[MAC_START:MAC_END]])[:-1]



你可能感兴趣的:(【Python】通过网卡(网桥)名称获取mac地址,针对多网卡情况)