br_system/
lib.rs

1use std::process::Command;
2
3#[cfg(target_os = "macos")]
4mod mac;
5#[cfg(target_os = "windows")]
6mod win;
7#[derive(Debug, Clone)]
8pub struct SystemInfo {
9    /// CPU核心数量
10    pub cores: usize,
11    /// 内存容量
12    pub memory: String,
13    /// 硬盘的序列号
14    pub serial_number: Vec<String>,
15    /// 硬件uuid
16    pub hardware_uuid: String,
17    /// 设备UUID
18    pub uuid: String,
19}
20
21impl SystemInfo {
22    pub fn new() -> Result<Self, String> {
23        let mut that = Self {
24            cores: 0,
25            memory: "".to_string(),
26            serial_number: vec![],
27            hardware_uuid: "".to_string(),
28            uuid: "".to_string(),
29        };
30        if cfg!(target_os = "macos") {
31            #[cfg(target_os = "macos")]
32            {
33                return that.mac_os();
34            }
35        }
36        if cfg!(target_os = "windows") {
37            #[cfg(target_os = "windows")]
38            {
39                return that.windows().cloned();
40            }
41        }
42        Ok(that)
43    }
44    #[cfg(target_os = "macos")]
45    pub fn mac_os(&mut self) -> Result<Self, String> {
46        self.uuid = mac::get_uuid().unwrap_or("".to_string());
47        self.serial_number = vec![self.uuid.clone()];
48        Ok(self.clone())
49    }
50
51    #[cfg(target_os = "windows")]
52    pub fn windows(&mut self) -> Result<&mut Self, String> {
53        // 硬盘序列号
54        let disk_output = match Command::new("powershell")
55            .args(&["(Get-WmiObject -Class Win32_ComputerSystemProduct).UUID.Trim()"])
56            .output() {
57            Ok(e) => e,
58            Err(e) => {
59                return Err(format!("{}", e.to_string()));
60            }
61        };
62        let serial_number = String::from_utf8_lossy(&disk_output.stdout);
63        for line in serial_number.lines() {
64            let text = line.trim();
65            self.uuid=text.to_string();
66        }
67        Ok(self)
68    }
69}