python 怎么获取电脑的mac地址
展开阅读全文

python 怎么获取电脑的mac地址

在 Linux 和 macOS 上获取 MAC 地址 您可以使用 scapy 库来获取网络接口和它们的 MAC 地址。scapy 是一个强大的数据包操作工具,可以用来发送、嗅探、分析和伪造网络数据包。

首先,您需要安装 scapy:

pip install scapy

然后,您可以使用以下代码来获取 MAC 地址:

from scapy.all import get_if_hwaddr  
  
def get_mac_address():  
    interfaces = get_if_list()  # 获取所有网络接口  
    for interface in interfaces:  
        try:  
            mac_address = get_if_hwaddr(interface)  
            return mac_address  
        except Exception as e:  
            print(f"无法获取 {interface} 的 MAC 地址: {e}")  
    return None  
  
mac_address = get_mac_address()  
if mac_address:  
    print(f"MAC 地址: {mac_address}")  
else:  
    print("无法获取 MAC 地址")

在 Windows 上获取 MAC 地址

在 Windows 上,您可以使用 wmi 库来获取 MAC 地址。wmi 是一个用于与 Windows Management Instrumentation (WMI) 交互的 Python 库。

首先,安装 wmi 库(如果尚未安装):

pip install wmi

然后,使用以下代码获取 MAC 地址:

import wmi  
  
def get_mac_address():  
    c = wmi.WMI()  
    for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):  
        return interface.MacAddress  
    return None  
  
mac_address = get_mac_address()  
if mac_address:  
    print(f"MAC 地址: {mac_address}")  
else:  
    print("无法获取 MAC 地址")