python 獲取mac地址的兩種方法

nbnb 9年前發布 | 1K 次閱讀 Python 太原維信科技,java

1)通用方法,借助uuid模塊

def get_mac_address():
  import uuid
      node = uuid.getnode()
      mac = uuid.UUID(int = node).hex[-12:]
  return mac

(2)按照操作系統平臺來

def get_mac_address():
    '''
    @summary: return the MAC address of the computer
    '''
    import sys
    import os
    mac = None
    if sys.platform == "win32":
        for line in os.popen("ipconfig /all"):
            print line
            if line.lstrip().startswith("Physical Address"):
                mac = line.split(":")[1].strip().replace("-", ":")
                break
    else:
        for line in os.popen("/sbin/ifconfig"):
            if 'Ether' in line:
                mac = line.split()[4]
                break
    return mac

需要提醒的是,方法一,也就是通過uuid來實現的方法適用性更強一些,因為通過解析popen的數據還受到系統語言環境的影響,比如在中文環境 下"ipconfig/all"的結果就包含有中文,要查找mac地址的話就不能查找Physical Address;而應該是“物理地址”

 本文由用戶 nbnb 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!