如何在Linux系统中通过C++获取PC的序列号或UUID?
当然可以!在Linux下虽然没有Windows那种统一的WMI API,但有几种靠谱的方式用C++获取硬件标识(比如BIOS序列号)来唯一标识机器。下面是最常用的两种方案:
方案1:读取sysfs虚拟文件系统
Linux通过sysfs暴露了大量硬件信息,其中就包含BIOS/产品序列号,路径通常是/sys/class/dmi/id/product_serial。这种方式无需依赖额外工具,直接读取文件即可。
C++代码示例
#include <iostream> #include <fstream> #include <string> #include <algorithm> std::string getBiosSerial() { std::ifstream serial_file("/sys/class/dmi/id/product_serial"); std::string serial; if (serial_file.is_open()) { std::getline(serial_file, serial); serial_file.close(); // 移除末尾的空白字符(换行、空格等) serial.erase(std::find_if(serial.rbegin(), serial.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), serial.end()); } else { serial = "无法读取序列号:可能需要root权限,或系统不支持DMI"; } return serial; } int main() { std::cout << "机器序列号:" << getBiosSerial() << std::endl; return 0; }
方案2:调用dmidecode工具(需root权限)
dmidecode是Linux下专门解析DMI(桌面管理接口)表的工具,能直接提取BIOS、主板、CPU等硬件信息。C++中可以通过popen执行该命令并读取输出。
前提条件
需要先安装dmidecode工具,比如在Debian/Ubuntu下执行:
sudo apt install dmidecode
C++代码示例
#include <iostream> #include <cstdio> #include <string> #include <algorithm> std::string getBiosSerialViaDmidecode() { char buffer[256]; std::string result; FILE* pipe = popen("sudo dmidecode -s system-serial-number", "r"); if (!pipe) { return "执行dmidecode失败:可能未安装或无root权限"; } while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { result += buffer; } pclose(pipe); // 清理空白字符 result.erase(std::find_if(result.rbegin(), result.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), result.end()); if (result.empty()) { result = "未获取到序列号:系统可能不支持DMI"; } return result; } int main() { std::cout << "机器序列号(通过dmidecode):" << getBiosSerialViaDmidecode() << std::endl; return 0; }
关键注意事项
- 权限问题:不管是读取sysfs文件还是调用dmidecode,几乎都需要root权限才能获取真实序列号,普通用户可能得到空值或默认占位符(比如
To be filled by O.E.M.)。 - 虚拟化环境:虚拟机的序列号通常由虚拟化平台生成,并非物理机的BIOS序列号,若要标识虚拟机,可考虑读取虚拟机特定的标识(比如VMware的UUID)。
- 兼容性:部分嵌入式Linux系统可能没有DMI表,此时可以考虑替代方案,比如读取CPU序列号(
/sys/devices/system/cpu/cpu0/serial)或网卡MAC地址(/sys/class/net/eth0/address),但MAC地址存在被修改的风险。
内容的提问来源于stack exchange,提问作者CH4




