1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::process::Command;

#[derive(Debug, Clone)]
pub struct SystemInfo {
    /// CPU核心数量
    pub cores: usize,
    /// 内存
    pub memory: String,
    /// 序列号
    pub serial_number: String,
    /// 硬件uuid
    pub hardware_uuid: String,
}

impl SystemInfo {
    pub fn new() -> Result<Self, String> {
        let mut that = Self {
            cores: 0,
            memory: "".to_string(),
            serial_number: "".to_string(),
            hardware_uuid: "".to_string(),
        };
        #[cfg(target_os = "macos")]
        return match that.mac_os() {
            Ok(e) => Ok(e.clone()),
            Err(e) => Err(e)
        };
        #[cfg(target_os = "windows")]
        return match that.windows() {
            Ok(e) => Ok(e.clone()),
            Err(e) => Err(e)
        };
        Err("无信息".to_string())
    }

    pub fn mac_os(&mut self) -> Result<&mut Self, String> {
        let output = match Command::new("system_profiler")
            .args(&["SPHardwareDataType"])
            .output() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("{}", e.to_string()));
            }
        };

        let serial_number = String::from_utf8_lossy(&output.stdout);
        for line in serial_number.lines() {
            let text = line.trim();
            if text.contains("Total Number of Cores: ") {
                self.cores = text.trim_start_matches("Total Number of Cores: ").parse::<usize>().unwrap();
            }
            if text.contains("Memory: ") {
                self.memory = text.trim_start_matches("Memory: ").to_string();
            }
            if text.contains("Serial Number (system): ") {
                self.serial_number = text.trim_start_matches("Serial Number (system): ").to_string();
            }
            if text.contains("Hardware UUID: ") {
                self.hardware_uuid = text.trim_start_matches("Hardware UUID: ").to_string();
            }
        }
        Ok(self)
    }

    pub fn windows(&mut self) -> Result<&mut Self, String> {
        let output = match Command::new("wmic")
            .args(&["diskdrive", "get", "SerialNumber"])
            .output() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("{}", e.to_string()));
            }
        };
        let serial_number = String::from_utf8_lossy(&output.stdout);
        println!("{}", serial_number);
        Err("none".to_string())
    }
}