【问题标题】:python - getting the MAC address properly in Windowspython - 在 Windows 中正确获取 MAC 地址
【发布时间】:2015-03-08 15:08:35
【问题描述】:

我使用的是 Windows 7 和 Python 2.6。我想获取我的网络接口的 MAC 地址。


我尝试过使用wmi 模块:

def get_mac_address():

    c = wmi.WMI ()
    for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
        return  interface.MACAddress

但是,在没有互联网连接的情况下执行时会遇到问题。


我尝试过使用uuid 模块:

from uuid import getnode 
print getnode()

但是,返回值是 MAC 地址的 48 字节表示

66610803803052

1) 我应该如何将给定的数字转换为ff:ff:ff:ff:ff:ff 格式?
2) 有没有更好的获取MAC地址的方法?

【问题讨论】:

  • 获得 UUID 的 MAC 是非常随机的(对我来说,它给出了 WLAN MAC)。

标签: python python-2.6 mac-address


【解决方案1】:

如果您有多个网络接口,则不能依赖 uuid 模块。 有一个跨平台的第三方库,名为getmac

安装:

pip install getmac

用法:

from getmac import get_mac_address
eth_mac = get_mac_address(interface="eth0")
win_mac = get_mac_address(interface="Ethernet 3")
ip_mac = get_mac_address(ip="192.168.0.1")
ip6_mac = get_mac_address(ip6="::1")
host_mac = get_mac_address(hostname="localhost")
updated_mac = get_mac_address(ip="10.0.0.1", network_request=True)

【讨论】:

    【解决方案2】:

    用 Python 2 试试这个:

    import uuid
    
    def get_mac():
      mac_num = hex(uuid.getnode()).replace('0x', '').upper()
      mac = '-'.join(mac_num[i : i + 2] for i in range(0, 11, 2))
      return mac
    
    print get_mac()
    

    如果您使用的是 Python 3,请尝试以下操作:

    import uuid
    
    def get_mac():
      mac_num = hex(uuid.getnode()).replace('0x', '').upper()
      mac = '-'.join(mac_num[i: i + 2] for i in range(0, 11, 2))
      return mac
    
    print (get_mac())
    

    【讨论】:

    • mac 很短的时候你要抓大小写。你必须 zfill() 它。 mac_num = hex(uuid.getnode()).replace('0x', '').replace('L', '')mac_num = mac_num.zfill(12)
    【解决方案3】:

    这行得通:

    >>> address = 1234567890
    >>> h = iter(hex(address)[2:].zfill(12))
    >>> ":".join(i + next(h) for i in h)
    '00:00:49:96:02:d2'
    

    或者:

    >>> "".join(c + ":" if i % 2 else c for i, c in enumerate(hex(address)[2:].zfill(12)))[:-1]
    '00:00:49:96:02:d2'
    

    或者:

    >>> h = hex(address)[2:].zfill(12)
    >>> ":".join(i + j for i, j in zip(h[::2], h[1::2]))
    '00:00:49:96:02:d2'
    

    您首先将数字转换为十六进制,将其填充为 12 个字符,然后将其转换为一系列两个字符字符串,然后用冒号将它们连接起来。但是,这取决于您的 MAC 查找方法的准确性。

    【讨论】:

      【解决方案4】:

      来自给定接口名称的 Mac 地址:

      https://gist.github.com/JayZar21/6f3fd031430d865d208c29ba55ce7ccb

      # Python 2:
      
      import socket
      import fcntl
      import struct
      
      def get_hw_address(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]
      
      # Python 3:
      
      import fcntl
      import socket
      import struct
      import binascii
      
      def get_hw_address(ifname):
          s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
          info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s',  bytes(ifname[:15], 'utf-8')))
          return ''.join(l + ':' * (n % 2 == 1) for n, l in enumerate(binascii.hexlify(info[18:24]).decode('utf-8')))[:-1]
      

      使用示例:

      get_hw_address("eth0")
      

      【讨论】:

      • 很好的解决方案,我稍作修改以具有与“uuid.getnode()”相似的返回值,即mac_str = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] return int(mac_str.translate(None, ":.- "), 16)
      【解决方案5】:

      没有第三方,迟到了! python 3,windows唯一解决方案:

      import subprocess, re
      
      ipconfig_all = subprocess.check_output('ipconfig /all').decode()
      mac_addr_pattern = re.compile(r'(?:[0-9a-fA-F]-?){12}')
      mac_addr_list = re.findall(mac_addr_pattern, ipconfig_all)
      
      print(mac_addr_list)
      

      【讨论】:

      • 这会错误地将其他字段检测为 MAC
      【解决方案6】:

      使用 Python 3 规范:

      >>> import uuid
      >>> mac_addr = hex(uuid.getnode()).replace('0x', '')
      >>> print(mac_addr)
      >>> 94de801e0e87
      >>> ':'.join(mac_addr[i : i + 2] for i in range(0, 11, 2))
      >>> '94:de:80:1e:0e:87
      

      或者

      print(':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1]))
      

      【讨论】:

        【解决方案7】:

        代码

        import re
        from uuid import getnode
        
        
        # to get physical address:
        original_mac_address = getnode()
        print("MAC Address: " + str(original_mac_address)) # this output is in raw format
        
        #convert raw format into hex format
        hex_mac_address = str(":".join(re.findall('..', '%012x' % original_mac_address)))
        print("HEX MAC Address: " + hex_mac_address)
        

        输出:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-07
          • 1970-01-01
          • 2010-10-23
          • 2014-07-24
          相关资源
          最近更新 更多