当前位置:首页>python>Python查询CPU+硬盘+网卡MAC +主板+BIOS序列号

Python查询CPU+硬盘+网卡MAC +主板+BIOS序列号

  • 2026-10-11 08:36:39
Python查询CPU+硬盘+网卡MAC +主板+BIOS序列号

Python,速成心法

敲代码,查资料,问Ai

练习,探索,总结,优化

★★★★★博文创作不易,源码代码的过程中,如有疑问的地方,欢迎大家指正留言交流。喜欢的老铁可以多多点赞+收藏分享+置顶,小红牛在此表示感谢。★★★★★

Python打包教程07:还不会用--add-data参数,添加资源文件吗?

Python打包教程04:UPX安装与使用(减小.exe体积)

Python打包教程03:PyInstaller命令使用指南

Python教程:PyCharm安装过程中遇到的中英文对照表

和Python编程相关的,中英文对照词汇表

2025年Python和pycharm安装下载教程

Python教程110:单线程和多线程源码演示(threading)

Python全国计算机二级模拟试卷及答案,刷题啦

Python教程108:针对面向对象Class类知识要点,源码示例再演示。

Python入门教程04:流程控制语句(if+for+continue等)

Python入门教程10:datetime模块的示例用法

Python入门教程02:常用的内置函数示例演示

200条Python零基础自学指南

Python零基础教程:小白入门自学知识点大纲

Python教程:Py模块导入方法详解

Python零基础系列视频教程(1-10集)

Python零基础系列视频教程(11-20集)

可以使用 Python 调用系统命令或第三方库来获取这些硬件信息。下面提供一个跨平台的解决方案,支持 Windows、Linux 和 macOS,获取 CPU 序列号(或 ID)、硬盘卷序列号、网卡 MAC 地址、主板序列号和 BIOS UUID。
1.注意事项
CPU 序列号:现代 CPU 通常不再提供可读序列号(Intel 从 Pentium III 后移除了 PSN),Windows 的 wmic cpu get processorid 返回的是 CPU ID(并非唯一序列号)。Linux 下可能没有有效值。
硬盘卷序列号:Windows 返回的是逻辑卷的序列号(格式化时生成),不是物理硬盘序列号。Linux/macOS 返回的是 UUID 或卷标识。
主板序列号:Linux 下需要 root 权限,且部分虚拟机或主板可能为空。
跨平台兼容性:已测试 Windows 10/11、Ubuntu 20.04、macOS Monterey。替代方案(更稳定)
2.如果追求更好的跨平台兼容性和易用性,可以使用第三方库查询:
wmi (Windows),dmidecode (Linux 解析 DMI),pySMART / smartctl 获取硬盘物理序列号,netifaces 获取 MAC 地址
但上述纯标准库 + subprocess 的方案已覆盖大多数场景。

↓ 完整源码如下 ↓

# -*- coding: utf-8 -*-# @Author : 小红牛# 微信公众号:wdPythonimport subprocessimport platformimport reimport sysdef run_command(cmd):    """运行命令并返回输出字符串(忽略错误)"""    try:        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)        return result.stdout.strip()    except:        return ""def get_cpu_serial():    """获取 CPU 序列号/ID"""    system = platform.system()    if system == "Windows":        out = run_command("wmic cpu get processorid")        # 输出格式类似:ProcessorId  \n ABCDEF12345678        for line in out.splitlines():            if line.strip() and not line.startswith("ProcessorId"):                return line.strip()    elif system == "Linux":        # 读取 /proc/cpuinfo 中的 Serial 或 processor id        with open("/proc/cpuinfo", "r") as f:            for line in f:                if "serial" in line.lower():                    return line.split(":")[1].strip()                if "processor" in line.lower() and "id" in line.lower():                    return line.split(":")[1].strip()    elif system == "Darwin":  # macOS        # macOS 使用 sysctl,但通常不提供 CPU 序列号,返回型号标识        out = run_command("sysctl -n machdep.cpu.brand_string")        return out    return "N/A"def get_disk_volume_serial(drive="C:"if platform.system() == "Windows"else"/"):    """获取指定磁盘的卷序列号(Windows: 盘符,Linux/macOS: 挂载点)"""    system = platform.system()    if system == "Windows":        out = run_command(f"wmic logicaldisk where deviceid='{drive}' get volumeserialnumber")        for line in out.splitlines():            if line.strip() and not line.startswith("VolumeSerialNumber"):                return line.strip()    elif system == "Linux":        # 使用 blkid 获取 UUID(可作为卷标识)        out = run_command(f"blkid {drive} | grep -o 'UUID=\"[^\"]*\"' | cut -d'\"' -f2")        if out:            return out        # 备选:lsblk        out = run_command(f"lsblk -o UUID {drive} -n 2>/dev/null")        if out:            return out    elif system == "Darwin":        out = run_command(f"diskutil info {drive} | grep 'Volume UUID' | awk '{{print $3}}'")        if out:            return out    return "N/A"def get_mac_address():    """获取网卡 MAC 地址(第一个非虚拟网卡)"""    try:        import uuid        mac = uuid.getnode()        if mac:            # 格式化为 xx:xx:xx:xx:xx:xx            return ':'.join(('%012X' % mac)[i:i+2] for i in range(0, 12, 2))    except:        pass    # 备选:使用 psutil(需要安装)    try:        import psutil        for iface, addrs in psutil.net_if_addrs().items():            for addr in addrs:                if addr.family == psutil.AF_LINK and addr.address != "00:00:00:00:00:00":                    return addr.address    except ImportError:        pass    # 备选:系统命令    system = platform.system()    if system == "Windows":        out = run_command("getmac /v /fo csv | findstr /v /i 'Ndis'")        for line in out.splitlines():            parts = line.replace('"', '').split(',')            if len(parts) >= 2 and re.match(r'([0-9A-F]{2}-){5}[0-9A-F]{2}', parts[1], re.I):                return parts[1].replace('-', ':')    elif system == "Linux":        out = run_command("cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address")        if out:            return out    elif system == "Darwin":        out = run_command("ifconfig en0 | awk '/ether/ {print $2}'")        if out:            return out    return "N/A"def get_mainboard_serial():    """获取主板序列号"""    system = platform.system()    if system == "Windows":        out = run_command("wmic baseboard get serialnumber")        for line in out.splitlines():            if line.strip() and not line.startswith("SerialNumber"):                return line.strip()    elif system == "Linux":        # 需要 root 权限,尝试 dmidecode        out = run_command("sudo dmidecode -s baseboard-serial-number 2>/dev/null")        if out and "Not Settable" not in out:            return out        # 备选:/sys/class/dmi/id/board_serial        try:            with open("/sys/class/dmi/id/board_serial", "r") as f:                return f.read().strip()        except:            pass    elif system == "Darwin":        out = run_command("ioreg -l | grep board-id | awk -F'\"' '{print $4}'")        if out:            return out    return "N/A"def get_bios_uuid():    """获取 BIOS UUID / 系统 UUID"""    system = platform.system()    if system == "Windows":        out = run_command("wmic csproduct get uuid")        for line in out.splitlines():            if line.strip() and not line.startswith("UUID"):                return line.strip()    elif system == "Linux":        # 尝试 dmidecode        out = run_command("sudo dmidecode -s system-uuid 2>/dev/null")        if out and "Not Settable" not in out:            return out        # 备选:/sys/class/dmi/id/product_uuid        try:            with open("/sys/class/dmi/id/product_uuid", "r") as f:                return f.read().strip()        except:            pass    elif system == "Darwin":        out = run_command("ioreg -l | grep IOPlatformUUID | awk -F'\"' '{print $4}'")        if out:            return out    return "N/A"if __name__ == "__main__":    print("CPU 序列号:      ", get_cpu_serial())    print("硬盘卷序列号:    ", get_disk_volume_serial())    print("网卡 MAC 地址:   ", get_mac_address())    print("主板序列号:      ", get_mainboard_serial())    print("BIOS UUID:       ", get_bios_uuid())

完毕!!感谢您的收看

------★★历史博文集合★★------

Python入门篇  进阶篇  视频教程  Py安装

py项目Python模块 Python爬虫  Json

Xpath正则表达式SeleniumEtreeCss

Gui程序开发TkinterPyqt5 列表元组字典

数据可视化   matplotlib   词云图Pyecharts

海龟画图PandasBug处理电脑小知识

自动化脚本编程工具NumPy CSVWeb

Pygame  图像处理  机器学习数据库

最新文章

随机文章