Try to execute 'dmidecode' command to get the system identifier first

This commit is contained in:
Iron-Yang
2024-07-03 22:46:59 +08:00
parent 7e218355f2
commit 995ff9b059
2 changed files with 18 additions and 20 deletions

3
.gitignore vendored
View File

@@ -1,3 +1,6 @@
target/* target/*
vnt/src/proto/* vnt/src/proto/*
common/src/generated_serial_number.rs common/src/generated_serial_number.rs
# RustRover
.idea

View File

@@ -52,6 +52,18 @@ pub fn get_unique_identifier() -> Option<String> {
pub fn get_unique_identifier() -> Option<String> { pub fn get_unique_identifier() -> Option<String> {
use std::process::Command; use std::process::Command;
// Try to execute 'dmidecode' command to get the system identifier first.
if let Ok(output) = Command::new("dmidecode")
.arg("-s")
.arg("system-uuid")
.output() {
let identifier = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if !identifier.is_empty() {
return Some(identifier.to_string());
}
}
// Try to read file /etc/machine-id if 'dmidecode' command cannot be executed or get nothing.
// 对 linux 或 wsl 来说,读取 /etc/machine-id 即可获取当前操作系统的 // 对 linux 或 wsl 来说,读取 /etc/machine-id 即可获取当前操作系统的
// 唯一标识,而且某些环境没有预装`dmidecode`命令 // 唯一标识,而且某些环境没有预装`dmidecode`命令
if let Ok(identifier) = std::fs::read_to_string("/etc/machine-id") { if let Ok(identifier) = std::fs::read_to_string("/etc/machine-id") {
@@ -61,22 +73,5 @@ pub fn get_unique_identifier() -> Option<String> {
} }
} }
let output = match Command::new("dmidecode")
.arg("-s")
.arg("system-uuid")
.output()
{
Ok(output) => output,
Err(_) => {
return None;
}
};
let result = String::from_utf8_lossy(&output.stdout);
let identifier = result.trim();
if identifier.is_empty() {
None None
} else {
Some(identifier.to_string())
}
} }