问题
I'm using Windows 7 and Python 2.6. I would like to get the MAC address of my network interface.
I've tried using the wmi
module:
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:
from uuid import getnode
print getnode()
However, return value is a 48 byte representation of the MAC address
66610803803052
1) How should I convert the given number to ff:ff:ff:ff:ff:ff
format?
2) Is there a better way to get the MAC address?
回答1:
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. However, this depends on the accuracy of your MAC-finding method.
回答2:
Try this with 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:
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())
回答3:
Using Python 3 specs:
>>> 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]))
回答4:
Mac address from a given interface name:
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")
回答5:
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:
回答6:
You cannot rely on the uuid
module If you have multiple network interfaces.
There's a 3rd party library that works cross-platform called 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)
回答7:
no third party, late to the party! python 3, windows only solution:
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)
来源:https://stackoverflow.com/questions/28927958/python-getting-the-mac-address-properly-in-windows