Myluzh Blog

python获取计算机MAC地址

发布时间: 2022-4-24 文章作者: myluzh 分类名称: Python 朗读文章


def get_mac():
    macList = list(net_if_addrs().items())
    macI = 0
    macAll = ""
    while True:
        try:
            macName = macList[macI][0]
            macAdders = macList[macI][1][0][1]
            #  macInfo = str(macName + " " + macAdders + " ")
            if validate_mac(macAdders):
                macAdders=macAdders.replace('-', ':')
                print(macName, macAdders)
            # macAll = macAll + macInfo
            macI = macI + 1
        except:
            break

#判断MAC合法性
def validate_mac(value):
    if value.find('-') != -1:
        pattern = re.compile(r"^\s*([0-9a-fA-F]{2,2}-){5,5}[0-9a-fA-F]{2,2}\s*$")
        if pattern.match(value):
            return True
        else:
            return False
    if value.find(':') != -1:
        pattern = re.compile(r"^\s*([0-9a-fA-F]{2,2}:){5,5}[0-9a-fA-F]{2,2}\s*$")
        if pattern.match(value):
            return True
        else:
            return False


if __name__ == "__main__":
    get_mac()

标签: python

发表评论