|
|
|
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();
|
|
|
|
System.out.println("当前操作系统:"+os);
|
|
|
|
// linux系统用Runtime.getRuntime().exec()执行 dmidecode -t processor 查询cpu序列
|
|
|
|
// windows系统用 wmic cpu get ProcessorId 查看cpu序列
|
|
|
|
if ("LINUX".equals(os)) {
|
|
|
|
cpuId = getLinuxCpuId("dmidecode -t processor | grep 'ID' | head -n 1", "ID", ":");
|
|
|
|
} 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);
|
|
|
|
System.out.println("获取命令执行结果:"+execResult);
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 获取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;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|