获取CPU、硬盘、主板序列号、MAC工具类

public class MachineSNUtils {/*** 获取主板序列号** @return*/public static String getMotherboardSN() {String result = "";try {File file = File.createTempFile("realhowto", ".vbs");file.deleteOnExit();FileWriter fw = new FileWriter(file);String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"+ "Set colItems = objWMIService.ExecQuery _ \n"+ "   (\"Select * from Win32_BaseBoard\") \n"+ "For Each objItem in colItems \n" + "    Wscript.Echo objItem.SerialNumber \n"+ "    exit for  ' do the first cpu only! \n" + "Next \n";fw.write(vbs);fw.close();String path = file.getPath().replace("%20", " ");Process p = Runtime.getRuntime().exec("cscript //NoLogo " + path);BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));String line;while ((line = input.readLine()) != null) {result += line;}input.close();} catch (Exception e) {e.printStackTrace();}return result.trim();}/*** 获取CPU序列号** @return*/public static String getCPUSerial() {String result = "";try {File file = File.createTempFile("tmp", ".vbs");file.deleteOnExit();FileWriter fw = new FileWriter(file);String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"+ "Set colItems = objWMIService.ExecQuery _ \n"+ "   (\"Select * from Win32_Processor\") \n"+ "For Each objItem in colItems \n" + "    Wscript.Echo objItem.ProcessorId \n"+ "    exit for  ' do the first cpu only! \n" + "Next \n";// + "    exit for  \r\n" + "Next";fw.write(vbs);fw.close();String path = file.getPath().replace("%20", " ");Process p = Runtime.getRuntime().exec("cscript //NoLogo " + path);BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));String line;while ((line = input.readLine()) != null) {result += line;}input.close();file.delete();} catch (Exception e) {e.fillInStackTrace();}if (result.trim().length() < 1 || result == null) {result = "无CPU_ID被读取";}return result.trim();}/*** 获取localhost的LANAddress** @return*/private static List<String> getLocalHostLANAddress()throws UnknownHostException, SocketException {List<String> ips = new ArrayList<String>();Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();while (interfs.hasMoreElements()) {NetworkInterface interf = interfs.nextElement();Enumeration<InetAddress> addres = interf.getInetAddresses();while (addres.hasMoreElements()) {InetAddress in = addres.nextElement();if (in instanceof Inet4Address) {//                    System.out.println("v4:" + in.getHostAddress());if (!"127.0.0.1".equals(in.getHostAddress())) {//连接VPN后,根据产生的ip查询MAC时,返回结果为null 因此获取IP时不要VPN产生的IPif (!interf.getName().contains("ppp")){ips.add(in.getHostAddress());}}}}}return ips;}/*** MAC* 通过jdk自带的方法,先获取本机所有的ip,然后通过NetworkInterface获取mac地址* 注意:连接VPN后,根据产生的ip查询MAC时,返回结果为null,需特殊处理** @return*/public static String getMac() {try {String resultStr = "";List<String> ls = getLocalHostLANAddress();int num = 0;for (String str : ls) {InetAddress ia = InetAddress.getByName(str);// 获取本地IP对象// 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();if (mac == null) {continue;}// 下面代码是把mac地址拼装成StringStringBuilder sb = new StringBuilder();for (int i = 0; i < mac.length; i++) {if (i != 0) {sb.append("-");}// mac[i] & 0xFF 是为了把byte转化为正整数String s = Integer.toHexString(mac[i] & 0xFF);sb.append(s.length() == 1 ? 0 + s : s);}if (num == ls.size() - 1) {resultStr += sb.toString().toUpperCase();} else {// 把字符串所有小写字母改为大写成为正规的mac地址并返回resultStr += sb.toString().toUpperCase() + ",";}num++;}return resultStr;} catch (Exception ex) {ex.printStackTrace();}return null;}/*** 获取硬盘序列号** @return*/public static String getHardDiskSN() {String line = "";String HdSerial = "";try {Process proces = Runtime.getRuntime().exec("cmd /c dir c:");BufferedReader buffreader = new BufferedReader(new InputStreamReader(proces.getInputStream(), "gbk"));while ((line = buffreader.readLine()) != null) {if (line.indexOf("卷的序列号是 ") != -1) {  //读取参数并获取硬盘序列号HdSerial = line.substring(line.indexOf("卷的序列号是 ") + "卷的序列号是 ".length());break;}}} catch (IOException e) {e.printStackTrace();}return HdSerial;}/***************************linux*********************************/public static String executeLinuxCmd(String cmd) {try {System.out.println("got cmd job : " + cmd);Runtime run = Runtime.getRuntime();Process process;process = run.exec(cmd);InputStream in = process.getInputStream();BufferedReader bs = new BufferedReader(new InputStreamReader(in));StringBuffer out = new StringBuffer();byte[] b = new byte[8192];for (int n; (n = in.read(b)) != -1; ) {out.append(new String(b, 0, n));}in.close();process.destroy();return out.toString();} catch (Exception e) {e.printStackTrace();}return null;}/*** @param cmd    命令语句* @param record 要查看的字段* @param symbol 分隔符* @return*/public static String getSerialNumber(String cmd, String record, String symbol) {String execResult = executeLinuxCmd(cmd);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;}/*** @param cmd    命令语句* @param record 要查看的字段* @param symbol 分隔符* @return*/public static String getAllSerialNumber(String cmd, String record, String symbol) {String execResult = executeLinuxCmd(cmd);String[] infos = execResult.split("\n");StringBuilder result = new StringBuilder();int k = 0;for (int i = 0; i < infos.length - 1; i++) {String info = infos[i];info = info.trim();if (info.indexOf(record) != -1) {info.replace(" ", "");String[] sn = info.split(symbol);if (k != 0) {result.append(',');}result.append(sn[1]);k++;}}if (k != 0) {return result.toString();} else {return null;}}/*** 判断是否为容器、虚拟机,返回虚拟ID** @return*/public static String getVirtualID() {String execResult = executeLinuxCmd("systemd-detect-virt");if (!execResult.contains("none")) {//docker容器String VirtualID = getSerialNumber("cat /proc/1/cgroup", "docker", "docker/");if (VirtualID != null) {return VirtualID;}//machine-rktVirtualID = getSerialNumber("cat /proc/1/cgroup", "machine-rkt", "machine-rkt\\");if (VirtualID != null) {VirtualID.replaceAll("\\x2d", "-");return VirtualID;}//vmwareVirtualID = getSerialNumber("dmidecode -t system", "UUID", ":");if (VirtualID != null) {return VirtualID;}return "UNKNOWN";}return null;}/*** 获取CPUID、硬盘序列号、MAC地址、主板序列号** @return*/public static Map<String, String> getAllSn() {String os = System.getProperty("os.name");os = os.toUpperCase();System.out.println("OS Name : " + os);Map<String, String> snVo = new HashMap<String, String>();if ("LINUX".equals(os)) {snVo.put("operating system", "LINUX");String virtualID = getVirtualID();if (virtualID != null) {if (virtualID.equals("UNKNOWN")) {System.out.println("UNKNOWN VMWARE!");return snVo;} else {System.out.println("virtualID : " + virtualID);snVo.put("virtualID", virtualID.toUpperCase().replace(" ", ""));String mac = getAllSerialNumber("ifconfig -a", "ether", " ");System.out.println("mac : " + mac);snVo.put("mac", mac.toUpperCase().replace(" ", ""));}} else {String cpuid = getSerialNumber("dmidecode -t processor | grep 'ID'", "ID", ":");System.out.println("cpuid : " + cpuid);String mainboardNumber =getSerialNumber("dmidecode |grep 'Serial Number'", "Serial Number", ":");System.out.println("mainboardNumber : " + mainboardNumber);String mac = getAllSerialNumber("ifconfig -a", "ether", " ");System.out.println("mac : " + mac);snVo.put("cpuid", cpuid.toUpperCase().replace(" ", ""));snVo.put("mac", mac.toUpperCase().replace(" ", ""));snVo.put("mainboard", mainboardNumber.toUpperCase().replace(" ", ""));}} else {snVo.put("operating system", "windows");String cpuid = getCPUSerial();String mainboard = getMotherboardSN();String disk = getHardDiskSN();String mac = getMac();System.out.println("CPU_SN : " + cpuid);System.out.println("MAINBOARD_SN : " + mainboard);System.out.println("CDISK_SN : " + disk);System.out.println("MAC_SN : " + mac);snVo.put("cpuid", cpuid.toUpperCase().replace(" ", ""));snVo.put("cdiskid", disk.toUpperCase().replace(" ", ""));snVo.put("mac", mac.toUpperCase().replace(" ", ""));snVo.put("mainboard", mainboard.toUpperCase().replace(" ", ""));}return snVo;}public static void main(String[] args) {getAllSn();}
}

参考文章地址:https://blog.csdn.net/linhaibing009/article/details/102524648

本文章修改了原帖中getLocalHostLANAddress()方法,增加对VPN连接的处理。由于连接VPN后,根据产生的ip查询MAC时,返回结果为null,做了特殊处理,即获取本机IP时,过滤掉VPN产生的IP。

获取CPU、硬盘、主板序列号及MAC地址工具类相关推荐

  1. JAVA获取CPUID、主板序列号、硬盘序列号、MAC地址

    最近在修改公司licence程序,需要获取到更多的硬件唯一标识,以便加密使用. 网上看了很多大神的博客,思路大概整理了一下,根据系统类型分为两种方式: 一.windows 通过创建vbs脚本,然后使用 ...

  2. java MacBook air,macbook pro 与 macbook air 的区别!(前者是高配?java中如何读取主板序列号、硬盘序列号、MAC地址...

    所以我想问的重点是?(本人使用苹果①向用于上网?整体性能呢:air那么薄,那么轻,请问它的硬盘对比pro有什么利弊,对于air我①直用macbook pro,②年换①次,今年由于①③寸的并没有使用i系 ...

  3. 一键获取电脑的系统安装时间、硬盘序列号、MAC地址、补丁安装信息

    查询Windows电脑的操作系统安装时间.硬盘序列号.MAC地址.补丁安装数量.和最新补丁安装时间,都有相应的命令行查询命令.但是一个一个查询有点麻烦,用Python写了一个一键查询的方法. 可将如下 ...

  4. Android Studio的代码笔记--SN序列号、MAC地址、IP地址学习

    关于获取设备SN序列号.MAC地址.IP地址的学习代码 SN序列号 获取SN序列号 MAC地址 获取MAC地址 IP.wlanIP.wlanMAC.网络.ping 获取以太网的IP地址 获取设备wla ...

  5. android arp工具,GitHub - SummerSnow274/ARP_sed_rev: 在Android通过ARP询问实现获取同一网络所有设备的MAC地址,AP隔离的网络除外...

    ARP_sed_rev 在Android通过ARP询问实现获取同一网络所有设备的MAC地址,AP隔离的网络除外 arpsed.c 编译:gcc arpsed.c -o arpsed 运行:sudo . ...

  6. 利用ioctl获取本机指定设备的MAC地址

    // 利用ioctl获取本机指定设备的MAC地址 #include<stdio.h> #include<string.h> #include<stdlib.h> # ...

  7. 本机磁盘序列号和MAC地址查询方法

    磁盘序列号查看方法 1.首先在开始菜单栏中输入cmd. 2.点击程序CMD. 3.然后输入diskpart并按下回车键,如下图所示. 4.接下来输入list disk,如下图所示.这样就可以看到我们的 ...

  8. 获取CPU型号和序列号

    主要参考文章:关于CPU序列号的问题,以及如何获取×64下CPU的ProcessorID_fudong071234的博客-CSDN博客前几天经过查资料,得到网络上获取CPU序列号的方法是错误的,首先我 ...

  9. 批处理获取本机IP(局域网)及MAC地址

    ::==================批处理获取本机IP(局域网)及MAC地址============== ::code by youxi01@bbs.bathome.cn 2008-1-5 @ec ...

  10. Java获取局域网中所有ip和Mac地址

    Java获取局域网中所有ip和Mac地址 定义一个Util public class IpAndMacUtil {/*** 获取本机Mac地址* @param ia* @return* @throws ...

最新文章

  1. Windows phone 7新开发工具发布
  2. CentOS 7.6 搭建Gitlab教程
  3. java 中gui的作用_java学习中最应该注意的Java GUI用户界面以何为基础
  4. mysql查询不同老师所教不同课程_mysql学习训练记录及笔记(二)
  5. EditPlus常用快捷键
  6. python 示例_Python TextCalendar类别| pryear()方法与示例
  7. 第1次在Flash Builder中写程序
  8. c语言题目详解——实现四舍五入
  9. 计算机毕业设计Java物料生产管理系统(源码+系统+mysql数据库+Lw文档)
  10. php 简单聊天室 实例,PHP简易聊天室实例
  11. Tungsten Fabric知识库丨更多组件内部探秘
  12. GC overhead limit exceeded 的解决方案与详情分析
  13. 金融贷款逾期的模型实现
  14. pAdTy_1 构建图形和动画应用程序
  15. 火车时刻表又更新了!
  16. 苹果屏幕录制没有声音_苹果手机屏幕不亮但有声音是怎么回事?不要慌,这样就可以解决...
  17. 小程序为什么要办理ICP许可证
  18. Android——待办事项(ToDoList)
  19. MBT测试思想在苏宁蛙测的运用实践分享
  20. form窗口上放一个label,如何能找到这个label在哪个文件中使用

热门文章

  1. spring源码下载以及gradle的详细使用教程
  2. 产品市场调研分析报告、竞品分析报告、产品体验报告的区别
  3. 随身WiFi改装天线折腾日记
  4. python实现微信自动发信息软件_Python实现给微信好友自动发送消息的示例
  5. 联想拯救者R720黑苹果EFI分享
  6. 《数据分析思维手册》和《数据分析师的职场真相》全集整理好啦,下载保存!...
  7. (完整版)c语言初学必背代码
  8. JDBC实战(一)JDBC概述
  9. 【蓝桥杯真题】2021年蓝桥杯省赛B组题目解析+代码(C/C++)
  10. 若依框架入门(前后端分离版本)