python 读取mac地址的实例代码

发布时间:2020-03-20编辑:脚本学堂
本文分享一段python代码,可用于读取mac地址,有需要的朋友,不妨参考下。

python实现读取mac地址,代码如下:
 

复制代码 代码示例:

#!/usr/bin/python
import os
import re
CmdLine = 'arp -n'
r = os.popen(CmdLine).read()
L = re.findall('10.26.12.1.*?([0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2})', r)
ret = L[0]
print ret

*****************************
import os
import re

def GetMac():
#Windows下的
    if os.name == 'nt':
        try:
            ret = ''
            CmdLine = 'ipconfig /all'
            r = os.popen(CmdLine).read()
            if r:
                L = re.findall('Physical Address.*?([0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2})', r)
                if len(L) > 0:
                    ret = L[0]
        except:
            pass
       
#linux/Unix下
    elif os.name == "posix":
        try:
            ret = ''
            CmdLine = 'ifconfig'
            r = os.popen(CmdLine).read()
            if r:
                L = re.findall('HWaddr.*?([0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2})', r)
                if len(L) > 0:
                    ret = L[0]
        except:
            pass
    else:
        pass
    return ret

if __name__ == '__main__':
    mac =  GetMac()
    print mac