package com.dky.security; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; 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(); } else { cpuId = getWindowsCpuId(); } String macK = cpuId.toUpperCase().replace(" ", ""); macK.replace(":",""); System.out.println( "本机mac地址:"+macK.replace(":","") ); return macK.replace(":",""); } /** * 获取linux系统CPU序列 */ public static String getLinuxCpuId() { String mac = ""; try { Process p = new ProcessBuilder("ifconfig").start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = br.readLine()) != null) { Pattern pat = Pattern.compile("\\b\\w+:\\w+:\\w+:\\w+:\\w+:\\w+\\b"); Matcher mat= pat.matcher(line); if(mat.find()) { mac=mat.group(0); } } br.close(); }catch (IOException e) { e.printStackTrace(); } System.out.println("本机mac地址:"+mac); return mac; } 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; } }