寻求跨平台(Windows及其他OS)获取MAC地址的最优Python方案
跨平台获取MAC地址的最优实现方案
核心实现思路
- 依赖Python标准库,避免引入第三方包,最大化兼容性
- 针对不同操作系统调用原生工具或读取系统文件,减少跨平台抽象层带来的兼容性隐患
- 过滤虚拟网卡、回环接口的无效MAC地址,只保留物理网卡的有效地址
- 适配权限边界:Linux下读取/sys目录无需特殊权限,Windows/macOS调用系统命令也无需管理员权限(部分特殊网卡可能例外)
Python代码实现
import platform import subprocess import csv from pathlib import Path def get_valid_mac_addresses(): """获取所有物理网卡的有效MAC地址,过滤虚拟/回环接口""" system = platform.system().lower() mac_addresses = [] if system == "windows": # 调用getmac命令获取详细网卡信息 result = subprocess.run( ["getmac", "/v", "/fo", "csv"], capture_output=True, text=True, check=True ) # 解析CSV输出 reader = csv.DictReader(result.stdout.splitlines()) for row in reader: mac = row["Physical Address"].strip() # 过滤虚拟网卡(包含VMware、VirtualBox、Hyper-V关键词) if "vmware" not in row["Network Adapter"].lower() and \ "virtualbox" not in row["Network Adapter"].lower() and \ "hyper-v" not in row["Network Adapter"].lower() and \ mac != "00-00-00-00-00-00": mac_addresses.append(mac) elif system == "linux": # 遍历/sys/class/net目录下的网卡接口 net_dir = Path("/sys/class/net") for interface in net_dir.iterdir(): # 排除回环接口和虚拟网卡(docker、veth、br-开头) if interface.name == "lo" or \ interface.name.startswith("docker") or \ interface.name.startswith("veth") or \ interface.name.startswith("br-"): continue # 读取MAC地址文件 addr_file = interface / "address" if addr_file.exists(): mac = addr_file.read_text().strip() if mac and mac != "00:00:00:00:00:00": mac_addresses.append(mac) elif system == "darwin": # 调用ifconfig命令获取网卡信息 result = subprocess.run( ["ifconfig"], capture_output=True, text=True, check=True ) output_lines = result.stdout.splitlines() current_interface = None for line in output_lines: # 识别en开头的物理网卡(macOS通常用en0、en1) if line.startswith("en") and ":" in line: current_interface = line.split(":")[0] # 提取MAC地址 if current_interface and "ether" in line: mac = line.split()[1].strip() if mac and mac != "00:00:00:00:00:00": mac_addresses.append(mac) current_interface = None # 避免重复添加 else: raise NotImplementedError(f"Unsupported operating system: {system}") return mac_addresses # 测试示例 if __name__ == "__main__": try: macs = get_valid_mac_addresses() print("物理网卡MAC地址:") for idx, mac in enumerate(macs, 1): print(f"{idx}. {mac}") except Exception as e: print(f"获取MAC地址失败:{str(e)}")
关键说明
- 兼容性:支持Windows、Linux、macOS三大主流平台,无需额外安装依赖
- 可靠性:通过关键词过滤虚拟网卡,确保返回的是物理设备的MAC
- 权限友好:大部分场景下无需管理员权限,Linux读取/sys目录是普通用户权限可访问的
- 异常处理:捕获命令执行失败、文件读取失败等异常,返回明确错误信息
内容的提问来源于stack exchange,提问作者kevin g
相关产品推荐
相关产品推荐

