You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.8 KiB

1 year ago
package com.dky.security;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class GetCpuInfo {
/**
* 获取当前系统CPU序列可区分linux系统和windows系统
*/
public static String getCpuId() throws Exception {
String cpuId;
// 获取当前操作系统名称
String os = System.getProperty("os.name");
os = os.toUpperCase();
1 year ago
System.out.println("当前操作系统:"+os);
1 year ago
// linux系统用Runtime.getRuntime().exec()执行 dmidecode -t processor 查询cpu序列
// windows系统用 wmic cpu get ProcessorId 查看cpu序列
if ("LINUX".equals(os)) {
1 year ago
cpuId = getLinuxCpuId("dmidecode -t processor | grep 'ID' | head -n 1", "ID", ":");
1 year ago
} else {
cpuId = getWindowsCpuId();
}
return cpuId.toUpperCase().replace(" ", "");
}
/**
* 获取linux系统CPU序列
*/
public static String getLinuxCpuId(String cmd, String record, String symbol) throws Exception {
String execResult = executeLinuxCmd(cmd);
1 year ago
System.out.println("获取命令执行结果:"+execResult);
1 year ago
String[] infos = execResult.split("\n");
for (String info : infos) {
info = info.trim();
if (info.indexOf(record) != -1) {
info.replace(" ", "");
String[] sn = info.split(symbol);
return sn[1];
}
}
return null;
}
1 year ago
public static String executeLinuxCmd(String cmd){
try {
Runtime run = Runtime.getRuntime();
Process process = null;
process = run.exec(cmd);
System.out.println(process.toString());
if (process == null){
System.out.println("未获取到执行结果");
}else {
System.out.println("读取执行结果");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 打印每一行输出
break;
}
reader.close();
process.destroy();
return line;
}
}catch (Exception e) {
e.printStackTrace();
1 year ago
}
1 year ago
return null;
1 year ago
}
/**
* 获取windows系统CPU序列
*/
public static String getWindowsCpuId() throws Exception {
Process process = Runtime.getRuntime().exec(
new String[]{"wmic", "cpu", "get", "ProcessorId"});
process.getOutputStream().close();
Scanner sc = new Scanner(process.getInputStream());
sc.next();
String serial = sc.next();
return serial;
}
}