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

package com.pro.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SerialNumberUtil {


/**
* 获取主板序列号
* @return
*/
public static String getMotherboardSN() {
String result = "";
try {
File file = File.createTempFile("realhowto", ".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.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();
}

/**
* 获取硬盘序列号(该方法获取的是 盘符的逻辑序列号,并不是硬盘本身的序列号)
* 硬盘序列号还在研究中
* @param drive 盘符
* @return
*/
public static String getHardDiskSN(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto", ".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);

String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+ "Set colDrives = objFSO.Drives\n"
+ "Set objDrive = colDrives.item(\""
+ drive
+ "\")\n"
+ "Wscript.Echo objDrive.SerialNumber"; // see note
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 java.io.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();
}

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())){
ips.add(in.getHostAddress());
}
}
}
}
return ips;
}

/**
* MAC
* 通过jdk自带的方法,先获取本机所有的ip,然后通过NetworkInterface获取mac地址
* @return
*/
public static String getMac() {
try {
String resultStr = "";
List<String> ls = getLocalHostLANAddress();
for(String str : ls){
InetAddress ia = InetAddress.getByName(str);// 获取本地IP对象
// 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
byte[] mac = NetworkInterface.getByInetAddress(ia)
.getHardwareAddress();
// 下面代码是把mac地址拼装成String
StringBuilder 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);
}
// 把字符串所有小写字母改为大写成为正规的mac地址并返回
resultStr += sb.toString().toUpperCase()+",";
}
return resultStr;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

/***************************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;
}

/**
* 获取CPUID、硬盘序列号、MAC地址、主板序列号
* @return
*/
public static Map<String, String> getAllSn(){
String os = System.getProperty("os.name");
os = os.toUpperCase();
System.out.println(os);

Map<String, String> snVo = new HashMap<String, String>();

if("LINUX".equals(os)) {
System.out.println("=============>for linux");
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 diskNumber = getSerialNumber("fdisk -l", "Disk identifier",":");
System.out.println("diskNumber : "+ diskNumber);
String mac = getSerialNumber("ifconfig -a", "ether"," ");

snVo.put("cpuid",cpuid.toUpperCase().replace(" ", ""));
snVo.put("diskid",diskNumber.toUpperCase().replace(" ", ""));
snVo.put("mac",mac.toUpperCase().replace(" ", ""));
snVo.put("mainboard",mainboardNumber.toUpperCase().replace(" ", ""));
}else {
System.out.println("=============>for windows");
String cpuid = SerialNumberUtil.getCPUSerial();
String mainboard = SerialNumberUtil.getMotherboardSN();
String disk = SerialNumberUtil.getHardDiskSN("c");
String mac = SerialNumberUtil.getMac();

System.out.println("CPU SN:" + cpuid);
System.out.println("主板 SN:" + mainboard);
System.out.println("C盘 SN:" + disk);
System.out.println("MAC SN:" + mac);

snVo.put("cpuid",cpuid.toUpperCase().replace(" ", ""));
snVo.put("diskid",disk.toUpperCase().replace(" ", ""));
snVo.put("mac",mac.toUpperCase().replace(" ", ""));
snVo.put("mainboard",mainboard.toUpperCase().replace(" ", ""));
}
System.out.println("=============>for windows");
String cpuid = SerialNumberUtil.getCPUSerial();
String mainboard = SerialNumberUtil.getMotherboardSN();
String disk = SerialNumberUtil.getHardDiskSN("c");
String mac = SerialNumberUtil.getMac();

System.out.println("CPU SN:" + cpuid);
System.out.println("主板 SN:" + mainboard);
System.out.println("C盘 SN:" + disk);
System.out.println("MAC SN:" + mac);

snVo.put("cpuid",cpuid.toUpperCase().replace(" ", ""));
snVo.put("diskid",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://www.cnblogs.com/gemiaomiao/p/10470903.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一般获取主板UID都是cmd命令 执行"wmic path Win32_ComputerSystemProduct get uuid" 这里说的是使用API获取,找了半天没找到,最后发现只能通过 GetSystemFirmwareTable 获取 SMBIOS信息 ,在这个结构体里存储的相当复杂,看的有点头晕 首先调用 GetSystemFirmwareTable  先让他返回结构体大小,然后我们申请一块内存,再调用一次,就会把  SMBIOS信息 存储到 我们申请的内存里了. SMBIOS信息 前8个字节就不看了,可以百度慢慢看,从第9个字节开始是TYPE结构,第一个字节是type类型,第二个字节就是这个type类型的大小,从type起始地址计算,后面的就是格式化区域,不同type类型格式化区域代表的信息也不同,格式化区域完后,就会跟一段u字符串,我们知道ascii字符串是0结尾,u字符串是00 结尾,字符串结尾后就是下一个type结构的开始了. 这里就只看下type1类型结构  从资料里看,在第8个字节后的16位就是uid了.   其他类型大家就自己查一下了. 里面的模块命令 就用了下 精益的十六进制转换命令,这个大家应该都有. 代码有点丑,见笑了. 系统信息 (Type 1) : SMBIOS 实现只关联一个单一的系统实例,并且包含且只包含一个系统信息结构。 位置 名称 长度 描述 00h TYPE 号 1BYTE 结构的TYPE 号,此处是1 01h 长度 1BYTE 格式区域总长度,2.0 版为08h ,2.1-2.3.4 版为19h,从2.4 版开始为1Bh 02h 句柄 2BYTE 指向本结构的句柄 04h 电脑制造商 1BYTE 一般为01h ,表示在字符串区域中的编号 05h 产品名称 1BYTE [url=]在字符串区域中的编号[/url] 06h 版本号 1BYTE 在字符串区域中的编号 07h 序列号 1BYTE 在字符串区域中的编号 09h UUID 16BYTE 通用唯一标识符 18h 唤醒类型 BYTE 用来标识导致系统开电启动的事件 19h SKU 号 BYTE 在字符串区域中的编号,SKU 号通常为产品ID 或采购订单号 1Ah 产品家族 1BYTE 在字符串区域中的编号

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值