Java获取终端设备信息工具类

news2025/4/15 22:05:28
  • 在很多场景中需要获取到终端设备的一些硬件信息等,获取的字段如下:

返回参数

参数含义备注
systemName系统名称
remoteIp公网ip
localIp本地ip取IPV4
macmac地址去掉地址中的"-“或”:"进行记录
cpuSerialcpu序列号
hardSerial硬盘序列号
drive盘符C
fileSystem分区格式NTFS
partitionSize分区容量119G
systemDisk系统盘卷标号
pcNamePC终端设备名称
pcSerialPC终端设备序列号仅Mac系统有,其余系统返回"null"
public final class HardInfoUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HardInfoUtils.class);

    /**
     * 获取系统名称-systemName
     *
     * @return 系统名称
     */
    public static String getSystemName() {
        return System.getProperty("os.name");
    }

    /**
     * 获取本地IP-localIp
     *
     * @return 本机 IP 地址
     * @throws RuntimeException 如果无法获取 IP 地址
     */
    public static String getLocalIp() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统:使用 WMI 查询 IP 地址
                return getWindowsLocalIp();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统:使用 ifconfig 命令
                return getLinuxLocalIp();
            } else if (os.contains("mac")) {
                // MacOS 系统:使用 ifconfig 命令
                return getMacLocalIp();
            } else {
                throw new RuntimeException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get localIp", e);
        }
    }

    /**
     * 获取公网 IP
     *
     * @return 公网 IP 地址,如果获取失败或格式不正确则返回 null
     */
    public static String getRemoteIp() {
        String os = System.getProperty("os.name").toLowerCase();
        String command = "curl ifconfig.me";
        if (os.contains("win")) {
            return executeWindowsCommand(command, ip -> {
                if (ip != null && isValidIp(ip)) {
                    return ip.trim();
                } else {
                    LOGGER.error("IP format is incorrect or null: {}", ip);
                    return null;
                }
            });
        } else {
            return executeCommandAndParseOutput(command, ip -> {
                if (ip != null && isValidIp(ip)) {
                    return ip.trim();
                } else {
                    LOGGER.error("IP format is incorrect or null: {}", ip);
                    return null;
                }
            });
        }
    }

    /**
     * Windows 系统:获取本地 IP 地址
     *
     * @return 本地 IP 地址
     */
    private static String getWindowsLocalIp() {
        String command = "wmic nicconfig where IPEnabled=true get IPAddress";
        return executeWindowsCommand(command, line -> {
            if (line.contains(".")) {
                String[] parts = line.split(",");
                for (String part : parts) {
                    part = part.replaceAll("[{}\"]", "").trim();
                    if (isValidIp(part)) {
                        return part;
                    }
                }
            }
            return null;
        });
    }

    /**
     * 检查 IP 地址是否有效
     *
     * @param ip IP 地址
     * @return 是否有效
     */
    private static boolean isValidIp(String ip) {
        String ipv4Regex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        Pattern pattern = Pattern.compile(ipv4Regex);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    /**
     * Linux 系统:获取本地 IP 地址
     *
     * @return 本地 IP 地址
     */
    private static String getLinuxLocalIp() {
        String command =
            "ifconfig | grep -E 'flags=|inet |broadcast ' | grep -i RUNNING -A 1 | grep 'inet ' | grep -m 1 " +
                "'broadcast ' | awk '{print $2}'";
        return executeCommandAndParseOutput(command, line -> line);
    }

    /**
     * MacOS 系统:获取本地 IP 地址
     *
     * @return 本地 IP 地址
     */
    private static String getMacLocalIp() {
        String command =
            "ifconfig | grep -E 'flags=|inet |broadcast ' | grep -i RUNNING -A 1 | grep 'inet ' | grep -m 1 " +
                "'broadcast ' | awk '{print $2}'";
        return executeCommandAndParseOutput(command, line -> line);
    }

    /**
     * 执行 Windows 命令并解析输出
     *
     * @param command         命令
     * @param outputProcessor 输出处理函数
     * @return 处理后的输出结果
     * @throws IOException IO 异常
     */
    private static String executeWindowsCommand(String command, Function<String, String> outputProcessor) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    String result = outputProcessor.apply(line.trim());
                    if (result != null) {
                        return result;
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to execute command: " + command, e);
        }
        return null;
    }

    /**
     * Linux或MacOS下执行命令并解析输出
     *
     * @param command 命令
     * @return 输出结果
     */
    private static String executeCommandAndParseOutput(String command, Function<String, String> outputProcessor) {
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.trim().isEmpty()) {
                        String out = outputProcessor.apply(line.trim());
                        if (out != null) {
                            return out;
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to execute command: " + command, e);
        }
        return null;
    }

    /**
     * 获取本机 MAC 地址-mac
     *
     * @return 本机 MAC 地址
     */
    public static String getMac() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统:使用 WMI 查询 MAC 地址
                return formatMac(getWindowsMac());
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统:使用 ifconfig 命令
                return formatMac(getLinuxMac());
            } else if (os.contains("mac")) {
                // MacOS 系统:使用 ifconfig 命令
                return formatMac(getMacOSMac());
            } else {
                throw new RuntimeException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get MAC address", e);
        }
    }

    /**
     * 格式化 MAC 地址为无分隔符的形式
     *
     * @param mac MAC 地址
     * @return 无分隔符的 MAC 地址
     */
    private static String formatMac(String mac) {
        if (mac == null || mac.isEmpty()) {
            return "";
        }
        // 移除所有分隔符(如 ":", "-")
        return mac.replaceAll("[:\\-]", "");
    }

    /**
     * Windows 系统:获取 MAC 地址
     *
     * @return MAC 地址
     */
    private static String getWindowsMac() {
        // 筛选出物理适配器,并且是已启用的状态
        String command = "wmic nic where \"PhysicalAdapter=True and NetEnabled=True\" get MACAddress /format:value";
        return executeWindowsCommand(command, line -> {
            if (line.startsWith("MACAddress=") && line.length() > "MACAddress=".length()) {
                // 清除前缀
                String macAddress = line.substring("MACAddress=".length()).trim();
                return macAddress.replace(":", "-");
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取 MAC 地址
     *
     * @return MAC 地址
     */
    private static String getLinuxMac() {
        String command =
            "ifconfig | grep -E 'flags=|inet |broadcast |ether ' | grep -i RUNNING -A 2 | grep -A 1 -E 'broadcast" +
                " " + "|inet ' | grep -m 1 'ether ' | awk '{print $2}'";
        return executeCommandAndParseOutput(command, line -> line);
    }

    /**
     * MacOS 系统:获取 MAC 地址
     *
     * @return MAC 地址
     */
    private static String getMacOSMac() {
        String command =
            "ifconfig | grep -E 'flags=|inet |broadcast |ether ' | grep -i RUNNING -A 2 | grep -B 1 -E 'broadcast" +
                " " + "|inet ' | grep -m 1 'ether ' | awk '{print $2}'";
        return executeCommandAndParseOutput(command, line -> line);
    }

    /**
     * 获取CPU序列号-cpuSerial
     *
     * @return CPU 序列号
     */
    public static String getCpuSerial() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统:使用 wmic 命令获取 CPU 序列号
                return getWindowsCpuSerial();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统:使用 dmidecode 命令获取 CPU 序列号
                return getLinuxCpuSerial();
            } else if (os.contains("mac")) {
                // macOS 系统:使用 system_profiler 命令获取 CPU 序列号
                return getMacCpuSerial();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get cpuSerial", e);
        }
    }

    /**
     * Windows 系统:获取 CPU 序列号
     *
     * @return CPU 序列号
     */
    private static String getWindowsCpuSerial() {
        String command = "wmic cpu get ProcessorId";
        return executeWindowsCommand(command, line -> {
            if (!line.isEmpty() && !line.contains("ProcessorId")) {
                return line;
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取 CPU 序列号
     *
     * @return CPU 序列号
     */
    private static String getLinuxCpuSerial() {
        String command = "dmidecode -t 4 | grep -m 1 ID | awk '{print $2$3$4$5$6$7$8$9}'";
        return executeCommandAndParseOutput(command, line -> {
            // 去掉所有空格
            String cpuSerial = line.replaceAll("\\s+", "");
            // 如果 CPU 序列号全为 0,则返回 null
            if ("0000000000000000".equals(cpuSerial)) {
                return null;
            }
            return cpuSerial;
        });
    }

    /**
     * macOS 系统:获取 CPU 序列号
     *
     * @return CPU 序列号
     */
    private static String getMacCpuSerial() {
        String command = "system_profiler SPHardwareDataType | grep -m 1 'Serial Number' | awk '{print $4}'";
        return executeCommandAndParseOutput(command, line -> {
            // 去掉所有空格
            return line.trim().replaceAll("\\s+", "");
        });
    }

    /**
     * 获取硬盘序列号-hardSerial
     *
     * @return 硬盘序列号
     */
    public static String getHardSerial() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统
                return getWindowsHardSerial();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统
                return getLinuxHardSerial();
            } else if (os.contains("mac")) {
                // macOS 系统
                return getMacHardSerial();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get hardSerial", e);
        }
    }

    /**
     * Windows 系统:获取硬盘序列号
     *
     * @return 硬盘序列号,如:6479_A75B_B090_09E0
     */
    private static String getWindowsHardSerial() {
        String command = "wmic diskdrive get serialnumber";
        return executeWindowsCommand(command, line -> {
            if (!line.trim().isEmpty() && !line.contains("SerialNumber")) {
                // 去掉末尾的点(如果存在)
                return line.trim().endsWith(".") ? line.trim().substring(0, line.length() - 1) : line.trim();
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取硬盘序列号
     *
     * @return 硬盘序列号,如:ac7b3398-162e-4775-b
     */
    private static String getLinuxHardSerial() {
        // Linux amd 执行后:SERIAL=""
        String command =
            "lsblk -p -P -o NAME,SERIAL,UUID,TYPE,MOUNTPOINT | grep -i boot -B 1 | grep -i disk | awk '{print $2}'";
        return executeCommandAndParseOutput(command, line -> {
            String result = line.trim().replace("SERIAL=", "").replace("\"", "");
            // 去掉末尾的点(如果存在)
            if (result.endsWith(".")) {
                result = result.substring(0, result.length() - 1);
            }
            // 如果序列号为空,返回 null
            return result.isEmpty() ? null : result;
        });
    }

    /**
     * macOS 系统:获取硬盘序列号
     *
     * @return 硬盘序列号
     */
    private static String getMacHardSerial() {
        String command = "system_profiler SPHardwareDataType | grep -m 1 'Hardware UUID' | awk '{print $3}'";
        return executeCommandAndParseOutput(command, line -> {
            String result = line.trim();
            // 去掉末尾的点(如果存在)
            if (result.endsWith(".")) {
                result = result.substring(0, result.length() - 1);
            }
            return result;
        });
    }

    /**
     * 获取系统盘盘符-drive
     *
     * @return 系统盘盘符,如:C 或 /dev/sda1
     * @throws RuntimeException 获取失败时抛出异常
     */
    public static String getDrive() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统
                return getWindowsDrive();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统
                return getLinuxDrive();
            } else if (os.contains("mac")) {
                // macOS 系统
                return getMacDrive();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get drive", e);
        }
    }

    /**
     * Windows 系统:获取盘符
     *
     * @return 盘符,如:C
     */
    private static String getWindowsDrive() {
        // 获取系统盘盘符(如 C:)
        String systemDrive = System.getenv("SystemDrive");
        if (systemDrive == null || systemDrive.isEmpty()) {
            LOGGER.error("SystemDrive environment variable is empty");
            return null;
        }
        // 去掉冒号
        return systemDrive.replace(":", "");
    }

    /**
     * Linux 系统:获取盘符
     *
     * @return 盘符,如:/dev/sda1
     */
    private static String getLinuxDrive() {
        String command =
            "lsblk -p -P -o NAME,PARTUUID,FSTYPE,SIZE,UUID,TYPE,MOUNTPOINT | grep -E '/boot\"$' | grep -i part | " +
                "awk " + "'{print $1,$2,$3,$4}'";
        return executeCommandAndParseOutput(command, line -> {
            String[] split = line.split("\"");
            return split.length > 1 ? split[1] : null;
        });
    }

    /**
     * macOS 系统:获取盘符
     *
     * @return 盘符
     */
    private static String getMacDrive() {
        String command = "system_profiler SPSoftwareDataType | grep -m 1 'Boot Volume'";
        return executeCommandAndParseOutput(command, line -> {
            String[] split = line.split(": ");
            return split.length > 1 ? split[1] : null;
        });
    }

    /**
     * 获取系统盘分区格式-fileSystem
     *
     * @return 系统盘分区格式,如:NTFS 或 xf4
     * @throws RuntimeException 如果无法获取分区格式
     */
    public static String getFileSystem() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统
                return getWindowsFileSystem();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统
                return getLinuxFileSystem();
            } else if (os.contains("mac")) {
                // macOS 系统
                return getMacFileSystem();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get fileSystem", e);
        }
    }

    /**
     * Windows 系统:获取分区格式
     *
     * @return 分区格式,如:NTFS
     */
    private static String getWindowsFileSystem() {
        // 获取系统盘盘符(如 C:)
        String systemDrive = System.getenv("SystemDrive");
        if (systemDrive == null || systemDrive.isEmpty()) {
            LOGGER.error("SystemDrive environment variable is empty");
            return null;
        }
        // 获取系统盘的分区信息
        String command = "wmic logicaldisk where deviceid='" + systemDrive + "' get filesystem";
        return executeWindowsCommand(command, line -> {
            if (!line.isEmpty() && !line.contains("FileSystem")) {
                return line;
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取分区格式
     *
     * @return 分区格式
     */
    private static String getLinuxFileSystem() {
        String command =
            "lsblk -p -P -o NAME,PARTUUID,FSTYPE,SIZE,UUID,TYPE,MOUNTPOINT | grep -E '/boot\"$' | grep -i part | " +
                "awk " + "'{print $1,$2,$3,$4}'";
        return executeCommandAndParseOutput(command, line -> {
            String[] split = line.split("\"");
            return split.length > 5 ? split[5] : null;
        });
    }

    /**
     * macOS 系统:获取分区格式
     *
     * @return 分区格式
     */
    private static String getMacFileSystem() {
        String command = "system_profiler SPStorageDataType | grep -w -A 5 -B 1 'Mount Point: /'";
        return executeCommandAndParseOutput(command, line -> {
            String number = "";
            String[] lines = line.split("\n");
            for (String l : lines) {
                l = l.trim();
                if (l.startsWith("File System:")) {
                    String[] split = l.split(" ");
                    if (split.length > 2) {
                        number = split[2];
                    }
                }
            }
            return number.isEmpty() ? null : number;
        });
    }

    /**
     * 获取系统盘分区容量
     *
     * @return 系统盘分区容量,如:119G
     * @throws RuntimeException 如果无法获取分区容量
     */
    public static String getPartitionSize() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统
                return getWindowsPartitionSize();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统
                return getLinuxPartitionSize();
            } else if (os.contains("mac")) {
                // macOS 系统
                return getMacPartitionSize();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get partition size", e);
        }
    }

    /**
     * Windows 系统:获取分区容量
     *
     * @return 分区容量
     */
    private static String getWindowsPartitionSize() {
        // 获取系统盘盘符(如 C:)
        String systemDrive = System.getenv("SystemDrive");
        if (systemDrive == null || systemDrive.isEmpty()) {
            LOGGER.error("SystemDrive environment variable is empty");
            return null;
        }
        // 获取系统盘的分区信息
        String command = "wmic logicaldisk where deviceid='" + systemDrive + "' get size";
        return executeWindowsCommand(command, line -> {
            if (!line.isEmpty() && !line.contains("Size")) {
                long sizeBytes = Long.parseLong(line);
                return (sizeBytes / 1024 / 1024 / 1024) + "G";
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取分区容量
     *
     * @return 分区容量
     */
    private static String getLinuxPartitionSize() {
        String command =
            "lsblk -p -P -o NAME,PARTUUID,FSTYPE,SIZE,UUID,TYPE,MOUNTPOINT | grep -E '/boot\"$' | grep -i part | " +
                "awk " + "'{print $1,$2,$3,$4}'";
        return executeCommandAndParseOutput(command, output -> {
            String[] split = output.split("\"");
            return split.length > 7 ? split[7] : null;
        });
    }

    /**
     * macOS 系统:获取分区容量
     *
     * @return 分区容量
     */
    private static String getMacPartitionSize() {
        String command = "system_profiler SPStorageDataType | grep -w -A 5 -B 1 'Mount Point: /'";
        return executeCommandAndParseOutput(command, line -> {
            String size = "";
            String[] lines = line.split("\n");
            for (String l : lines) {
                l = l.trim();
                if (l.startsWith("Capacity:")) {
                    String[] split = l.split(" ");
                    if (split.length > 1) {
                        size = split[1] + "G";
                    }
                }
            }
            return size;
        });
    }

    /**
     * 获取系统盘卷标号-systemDisk
     *
     * @return 系统盘卷标号
     */
    public static String getSystemDisk() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统
                return getWindowsSystemDisk();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统
                return getLinuxSystemDisk();
            } else if (os.contains("mac")) {
                // macOS 系统
                return getMacSystemDisk();
            } else {
                throw new UnsupportedOperationException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get systemDisk", e);
        }
    }

    /**
     * Windows 系统:获取系统盘卷标号
     *
     * @return 系统盘卷标号,格式为 "XXXX-XXXX",如:8AD0-CC8B
     */
    private static String getWindowsSystemDisk() {
        // 获取系统盘盘符(如 C:)
        String systemDrive = System.getenv("SystemDrive");
        if (systemDrive == null || systemDrive.isEmpty()) {
            LOGGER.error("SystemDrive environment variable is empty");
            return null;
        }

        // 获取系统盘的卷标号
        String command = "wmic logicaldisk where deviceid='" + systemDrive + "' get VolumeSerialNumber";
        return executeWindowsCommand(command, line -> {
            if (!line.isEmpty() && !line.contains("VolumeSerialNumber")) {
                if (line.length() == 8) {
                    // 格式化为 XXXX-XXXX
                    return line.substring(0, 4) + "-" + line.substring(4);
                }
            }
            return null;
        });
    }

    /**
     * Linux 系统:获取系统盘卷标号
     *
     * @return 系统盘卷标号
     */
    private static String getLinuxSystemDisk() {
        // 使用 lsblk 命令获取系统盘卷标号
        // Linux amd执行后:UUID="" LABEL=""
        String command =
            "lsblk -p -P -o NAME,UUID,LABEL,TYPE,MOUNTPOINT | grep -i boot -B 1 | grep -i disk | awk '{print $2," +
                "$3}'";
        return executeCommandAndParseOutput(command, line -> {
            String[] parts = line.trim().split("\"");
            if (parts.length >= 4) {
                // UUID
                String uuid = parts[1];
                // LABEL
                String label = parts[3];
                // 返回 UUID 或 LABEL
                return !uuid.isEmpty() ? uuid : label;
            }
            return null;
        });
    }

    /**
     * macOS 系统:获取系统盘卷标号
     *
     * @return 系统盘卷标号
     */
    private static String getMacSystemDisk() {
        String command = "system_profiler SPStorageDataType | grep -w -A 5 -B 1 'Mount Point: /'";
        return executeCommandAndParseOutput(command, line -> {
            String number = "";
            String[] lines = line.split("\n");
            for (String l : lines) {
                l = l.trim();
                if (l.startsWith("Volume UUID:")) {
                    String[] split = l.split(" ");
                    if (split.length > 2) {
                        number = split[2];
                    }
                }
            }
            return number.isEmpty() ? null : number;
        });
    }

    /**
     * 获取PC终端设备名称-pcName
     *
     * @return PC终端设备名称
     */
    public static String getPcName() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统:使用 hostname 命令获取设备名称
                String command = "hostname";
                return executeWindowsCommand(command, line -> line.isEmpty() ? null : line);
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux 系统:使用 hostname 命令获取设备名称
                return executeCommandAndParseOutput("hostname", line -> line);
            } else if (os.contains("mac")) {
                // MacOS 系统:使用 scutil 命令获取设备名称
                return executeCommandAndParseOutput("scutil --get ComputerName", line -> line);
            } else {
                throw new RuntimeException("Unsupported operating system: " + os);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get pcName.", e);
        }
    }

    /**
     * 获取PC终端设备序列号(仅 Mac 系统有,其他系统返回 "null")
     *
     * @return PC 终端设备序列号,如果获取失败或非 Mac 系统则返回 "null"
     */
    public static String getPcSerial() {
        String os = System.getProperty("os.name").toLowerCase();
        if (!os.contains("mac")) {
            // 非 Mac 系统直接返回 "null"
            return "null";
        }
        try {
            // MacOS 系统:使用 system_profiler 命令获取设备序列号
            String command = "system_profiler SPHardwareDataType | grep -m 1 'Provisioning UDID' | awk '{print $3}'";
            return executeCommandAndParseOutput(command, line -> line);
        } catch (Exception e) {
            throw new RuntimeException("Failed to get pcSerial on MacOS.", e);
        }
    }

}

  • 测试下本地Windows
public class HardInfoUtilsTest {

    public static void main(String[] args) {
        System.out.println("systemName: " + HardInfoUtils.getSystemName());
        System.out.println("localIp: " + HardInfoUtils.getLocalIp());
        System.out.println("remoteIp: " + HardInfoUtils.getRemoteIp());
        System.out.println("mac: " + HardInfoUtils.getMac());
        System.out.println("cpuSerial: " + HardInfoUtils.getCpuSerial());
        System.out.println("hardSerial: " + HardInfoUtils.getHardSerial());
        System.out.println("drive: " + HardInfoUtils.getDrive());
        System.out.println("fileSystem: " + HardInfoUtils.getFileSystem());
        System.out.println("partitionSize: " + HardInfoUtils.getPartitionSize());
        System.out.println("systemDisk: " + HardInfoUtils.getSystemDisk());
        System.out.println("pcName: " + HardInfoUtils.getPcName());
        System.out.println("pcSerial: " + HardInfoUtils.getPcSerial());
    }

}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2334771.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Linux网络与网络编程】08.传输层协议 UDP

传输层协议负责将数据从发送端传输到接收端。 一、再谈端口号 端口号标识了一个主机上进行通信的不同的应用程序。在 TCP/IP 协议中&#xff0c;用 "源IP"&#xff0c;"源端口号"&#xff0c;"目的 IP"&#xff0c;"目的端口号"&…

没音响没耳机,把台式电脑声音播放到手机上

第一步&#xff0c;电脑端下载安装e2eSoft VSC虚拟声卡&#xff08;安装完成后关闭&#xff0c;不要点击和设置&#xff09; 第二步&#xff0c;电脑端下载安装&#xff08;SoundWire Server&#xff09;&#xff08;安装完成后不要关闭&#xff0c;保持默认配置&#xff09; 第…

XDocument和XmlDocument的区别及用法

因为这几天用到了不熟悉的xml统计数据&#xff0c;啃了网上的资料解决了问题&#xff0c;故总结下xml知识。 1.什么是XML?2.XDocument和XmlDocument的区别3.XDocument示例1示例2&#xff1a;示例3&#xff1a; 4.XmlDocument5.LINQ to XML6.XML序列化(Serialize)与反序列化(De…

Blender安装基础使用教程

本博客记录安装Blender和基础使用&#xff0c;可以按如下操作来绘制标靶场景、道路标识牌等。 目录 1.安装Blender 2.创建面板资源 步骤 1: 设置 Blender 场景 步骤 2: 创建一个平面 步骤 3: 将 PDF 转换为图像 步骤 4-方法1: 添加材质并贴图 步骤4-方法2&#xff1a;创…

【Git】从零开始使用git --- git 的基本使用

哪怕是野火焚烧&#xff0c;哪怕是冰霜覆盖&#xff0c; 依然是志向不改&#xff0c;依然是信念不衰。 --- 《悟空传》--- 从零开始使用git 了解 Gitgit创建本地仓库初步理解git结构版本回退 了解 Git 开发场景中&#xff0c;文档可能会经历若干版本的迭代。假如我们不进行…

Android 中支持旧版 API 的方法(API 30)

Android 中最新依赖库的版本支持 API 31 及以上版本&#xff0c;若要支持 API30&#xff0c;则对应的依赖库的版本就需要使用旧版本。 可通过修改模块级 build.gradle 文件来进行适配。 1、android 标签的 targetSdk 和 compileSdk 版本号 根据实际目标设备的 android 版本来…

[特殊字符] Hyperlane:Rust 高性能 HTTP 服务器库,开启 Web 服务新纪元!

&#x1f680; Hyperlane&#xff1a;Rust 高性能 HTTP 服务器库&#xff0c;开启 Web 服务新纪元&#xff01; &#x1f31f; 什么是 Hyperlane&#xff1f; Hyperlane 是一个基于 Rust 语言开发的轻量级、高性能 HTTP 服务器库&#xff0c;专为简化网络服务开发而设计。它支…

RIP V2路由协议配置实验CISCO

1.RIP V2简介&#xff1a; RIP V2&#xff08;Routing Information Protocol Version 2&#xff09;是 RIP 路由协议的第二版&#xff0c;属于距离矢量路由协议&#xff0c;主要用于中小型网络环境。相较于 RIP V1&#xff0c;RIP V2 在功能和性能上进行了多项改进&#xff0c…

《LNMP架构+Nextcloud私有云超维部署:量子级安全与跨域穿透实战》

项目实战-使用LNMP搭建私有云存储 准备工作 恢复快照&#xff0c;关闭安全软件 [rootserver ~]# setenforce 0[rootserver ~]# systemctl stop firewalld搭建LNMP环境 [rootserver ~]# yum install nginx mariadb-server php* -y# 并开启nginx服务并设置开机自启 [r…

3DMAX笔记-UV知识点和烘焙步骤

1. 在展UV时&#xff0c;如何点击模型&#xff0c;就能选中所有这个模型的uv 2. 分多张UV时&#xff0c;不同的UV的可以设置为不同的颜色&#xff0c;然后可以通过颜色进行筛选。 3. 烘焙步骤 摆放完UV后&#xff0c;要另存为一份文件&#xff0c;留作备份 将模型部件全部分成…

【新人系列】Golang 入门(十三):结构体 - 下

✍ 个人博客&#xff1a;https://blog.csdn.net/Newin2020?typeblog &#x1f4dd; 专栏地址&#xff1a;https://blog.csdn.net/newin2020/category_12898955.html &#x1f4e3; 专栏定位&#xff1a;为 0 基础刚入门 Golang 的小伙伴提供详细的讲解&#xff0c;也欢迎大佬们…

Spring Boot 自定义商标(Logo)的完整示例及配置说明( banner.txt 文件和配置文件属性信息)

Spring Boot 自定义商标&#xff08;Logo&#xff09;的完整示例及配置说明 1. Spring Boot 商标&#xff08;Banner&#xff09;功能概述 Spring Boot 在启动时会显示一个 ASCII 艺术的商标 LOGO&#xff08;默认为 Spring 的标志&#xff09;。开发者可通过以下方式自定义&a…

Ubuntu虚拟机Linux系统入门

目录 一、安装 Ubuntu Linux 20.04系统 1.1 安装前准备工作 1.1.1 镜像下载 1.1.2 创建新的虚拟机 二、编译内核源码 2.1 下载源码 2.2 指定编译工具 2.3 将根文件系统放到源码根目录 2.4 配置生成.config 2.5 编译 三、安装aarch64交叉编译工具 四、安装QEMU 五、…

【蓝桥杯】2025省赛PythonB组复盘

前言 昨天蓝桥杯python省赛B组比完&#xff0c;今天在洛谷上估了下分&#xff0c;省一没有意外的话应该是稳了。这篇博文是对省赛试题的复盘&#xff0c;所给代码是省赛提交的代码。PB省赛洛谷题单 试题 A: 攻击次数 思路 这题目前有歧义&#xff0c;一个回合到底是只有一个…

【数据结构_4下篇】链表

一、链表的概念 链表&#xff0c;不要求在连续的内存空间&#xff0c;链表是一个离散的结构。 链表的元素和元素之间&#xff0c;内存是不连续的&#xff0c;而且这些元素的空间之间也没有什么规律&#xff1a; 1.顺序上没有规律 2.内存空间上也没有规律 *如何知道链表中包…

音视频 五 看书的笔记 MediaCodec

MediaCodec 用于访问底层媒体编解码器框架&#xff0c;编解码组件。通常与MediaExtractor(解封装,例如Mp4文件分解成 video和audio)、MediaSync、MediaMuxer(封装 例如音视频合成Mp4文件)、MediaCrypto、Image(cameraX 回调的ImageReader对象可以获取到Image帧图像,可转换成YU…

ubuntu 系统安装Mysql

安装 mysql sudo apt update sudo apt install mysql-server 启动服务 sudo systemctl start mysql 设置为开机自启 sudo systemctl enable mysql 查看服务状态 &#xff08;看到类似“active (running)”的状态信息代表成功&#xff09; sudo systemctl status mysql …

selenium快速入门

一、操作浏览器 from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By# 设置选项 q1 Options() q1.add_argument("--no-sandbo…

Redis:线程模型

单线程模型 Redis 自诞生以来&#xff0c;一直以高性能著称。很多人好奇&#xff0c;Redis 为什么早期采用单线程模型&#xff0c;它真的比多线程还快吗&#xff1f; 其实&#xff0c;Redis 的“快”并不在于并发线程&#xff0c;而在于其整体架构设计极致简单高效&#xff0c;…

Transformer模型解析与实例:搭建一个自己的预测语言模型

目录 1. 前言 2. Transformer 的核心结构 2.1 编码器&#xff08;Encoder&#xff09; 2.2 解码器&#xff08;Decoder&#xff09; 2.3 位置编码&#xff08;Positional Encoding&#xff09; 3. 使用 PyTorch 构建 Transformer 3.1 导入所需的模块&#xff1a; 3.2 定…