简体   繁体   English

python - 在Windows中正确获取MAC地址

[英]python - getting the MAC address properly in Windows

I'm using Windows 7 and Python 2.6. 我正在使用Windows 7和Python 2.6。 I would like to get the MAC address of my network interface. 我想获得我的网络接口的MAC地址。


I've tried using the wmi module: 我尝试过使用wmi模块:

def get_mac_address():

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

However, experienced issues when executed without internet connectivity. 但是,没有互联网连接时执行时遇到问题。


I've tried using the uuid module: 我尝试过使用uuid模块:

from uuid import getnode 
print getnode()

However, return value is a 48 byte representation of the MAC address 但是,返回值是MAC地址的48字节表示

66610803803052

1) How should I convert the given number to ff:ff:ff:ff:ff:ff format? 1)我应该如何将给定的数字转换为ff:ff:ff:ff:ff:ff格式?
2) Is there a better way to get the MAC address? 2)有更好的方法来获取MAC地址吗?

Try this with Python 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()

If you're using Python 3, try this: 如果您使用的是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())

This works: 这有效:

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

Or: 要么:

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

Or: 要么:

>>> 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'

You first convert the number to hex, pad it to 12 chars, and then convert it to a series of two char strings, and then join them with colons. 首先将数字转换为十六进制,将其填充为12个字符,然后将其转换为一系列两个字符串,然后将它们与冒号连接。 However, this depends on the accuracy of your MAC-finding method. 但是,这取决于MAC查找方法的准确性。

Using Python 3 specs: 使用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

Or 要么

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

Mac address from a given interface name: 来自给定接口名称的Mac地址:

https://gist.github.com/JayZar21/6f3fd031430d865d208c29ba55ce7ccb 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]

Usage example: 用法示例:

get_hw_address("eth0")

code : 代码

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)

Output: 输出:

我的输出:

You cannot rely on the uuid module If you have multiple network interfaces. 您不能依赖uuid模块如果您有多个网络接口。 There's a 3rd party library that works cross-platform called getmac 有一个名为getmac的跨平台工作的第三方库

Installation: 安装:

pip install getmac

Usage: 用法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM