首页 > 解决方案 > 如何在 Java 中查找 Linux 操作系统的 UUID 和序列号

问题描述

我正在尝试查找 linux 操作系统的 UUID。下面是我正在尝试的代码,它给出了空值..

 public static String getUUIDForLinux() {
   StringBuffer output = new StringBuffer();
        Process process;
        String[] cmd = {"/bin/sh", "-c", "sudo -S cat /sys/class/dmi/id/product_uuid"};
        try {
            process = Runtime.getRuntime().exec(cmd);
          //  process.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
           log.error(e.getMessage(),e);
            
        }
        log.info("uuid for linux:"+output.toString());
        return output.toString();       
}

使用以下代码获取序列号。我在这段代码中做错了什么..

  public static String getSerialNumHDForLinux() {
    String machineIdLinux = "";
    
    try {
        StringBuffer output = new StringBuffer();

        Process p = Runtime.getRuntime().exec("/bin/bash -c\"hdparm -I /dev/sda | grep Serial\"");
        BufferedReader sNumReader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = sNumReader.readLine()) != null) {
            output.append(line + "\n");
        }
        machineIdLinux =output.toString().substring(output.indexOf("\n"), output.length()).trim();
       
    }catch(IOException e) {
        log.error(e.getMessage());
    }
     return machineIdLinux;
}

有人请帮我更正代码..

标签: javalinuxuuid

解决方案


此代码适用于获取 linux 机器的 UUID。

 public static String getUUIDForLinux() {
   StringBuffer output = new StringBuffer();
        Process process;
        try {
            process = Runtime.getRuntime().exec("cat /sys/class/dmi/id/product_uuid");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
           log.error(e.getMessage(),e);
            
        }
        log.info("uuid for linux:"+output.toString());
        return output.toString();      

}

为了根据我们的服务器获取序列号,我使用了以下命令:上述代码中的 cat /sys/class/dmi/id/product_serial。


推荐阅读