获取电脑唯一标识,硬盘序列号,主板序列号,CPU序列号

news/2024/11/15 1:33:16/

在生产环境中,有时候会需要获取电脑唯一标识进行程序管理验证,比如一个程序,在A电脑上面只能允许正常登陆一年,到期后提示联系管理员等情况。就是获取电脑唯一标识后将该值存入授权数据库,默认给当前电脑的使用时期为当前时间后一年,一年后登陆时不能正常登陆(记录第一次使用这种场景)
java代码

package org.wj.common.tool;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;public class SerialNumberUtil {/*** 获取主板序列号* @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();}/*** 获取硬盘序列号(该方法获取的是 盘符的逻辑序列号,并不是硬盘本身的序列号)* 硬盘序列号还在研究中* @param drive 盘符* @return*/public static String getHardDiskSN(String drive) {String result = "";try {File file = File.createTempFile("realhowto", ".vbs");file.deleteOnExit();FileWriter fw = new 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 notefw.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();}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地址拼装成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);}// 把字符串所有小写字母改为大写成为正规的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(" ", ""));}return snVo;}/*** linux* cpuid : dmidecode -t processor | grep 'ID'* mainboard : dmidecode |grep 'Serial Number'* disk : fdisk -l* mac : ifconfig -a* @param args*/public static void main(String[] args) {getAllSn();}/*** @Description:获取唯一标识* @Param: []* @return: java.lang.String* @Author: wj* @Date: 2019-09-04*/public static String  getmainboard() {//主板idString mainboard=null;//C盘idString disk=null;//macidString mac=null;Map<String, String>  sno=SerialNumberUtil.getAllSn();for(String key : sno.keySet()){String value = sno.get(key);if(("mainboard").equals(key)){mainboard=value;}else if(("diskid").equals(key)){disk=value;}}return mainboard+disk;}public  static  String nextYear(){Date date = new Date();Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.YEAR, 1);//增加一年SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);//java.util.Date对象Date date1=new Date();try {date1 = (Date) sdf.parse(cal.getTime().toString());} catch (ParseException e) {e.printStackTrace();}String formatStr2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date1);return formatStr2;}
``代码链接:
https://download.csdn.net/download/weixin_44244991/12477368

http://www.ppmy.cn/news/301077.html

相关文章

98dx166switch交换芯片接口移植(一):SMI接口以及MII接口

一&#xff1a;交换机的原理机制 信号转发的网络设备&#xff0c;介入交换机的任意两个节点共享信号通路&#xff0c;工作与OSI的数据链路层&#xff0c;同事可以进行多个端口的数据传输&#xff0c;交换机上电后会自动创建一个端口地址表&#xff0c;叫做MAC地址表&#xff0…

w25q64 linux,QSPI读写W25Q256和W25Q128以及W25Q64有什么区别?

本帖最后由 ssmart 于 2018-9-4 16:27 编辑 用QSPI实验程序&#xff0c;换成Q128后有修改相关参数&#xff0c;实验主体程序如下: while(1) { keyKEY_Scan(0); if(keyKEY1_PRES)//KEY1按下,写入W25Q128 { LCD_Fill(0,320,800,160,BLACK);//清除半屏 LCD_DispStr…

英特尔CPU命名详解:32个后缀名、8个系列,如12700F等

英特尔家族的CPU总共有8个“系列”&#xff0c;分别是至强(Xeon)、至强融核(Xeon Phi)、酷睿(Core)、奔腾(Pentium)、赛扬(Celeron)、凌动(Atom)、安腾(itanium)、Quark™ SoC。 Intel Core™ i7-1195G7就属于酷睿系列的CPU 总体来说&#xff0c;酷睿、赛扬、奔腾属于消费级C…

JMS578开PS3111固件方法,SATA/USB通用,附群联PS3111量产开卡软件

买了个PS3111工具快两年了&#xff0c;一直玩不出来&#xff0c;今天算搞明白了一点&#xff0c;贴了片L06B的颗粒&#xff0c;试验N遍都是1153E&#xff0c;我是玩不出来。 最开始就怀疑固件问题了。网上出的U盘板子大部分都是578桥接&#xff0c;这个就好办了&#xff0c;咱…

通过WMI获取网卡MAC地址、硬盘序列号、主板序列号、CPU ID、BIOS序列号

开发语言&#xff1a;C/C 支持平台&#xff1a;Windows 实现功能&#xff1a; 通过WMI获取网卡MAC地址、硬盘序列号、主板序列号、CPU ID、BIOS序列号 下载地址&#xff1a; WMI_DeviceQuery.zip 版本历史&#xff1a; V1.4 2010年05月17日 修正了硬盘序列号处理中的错误…

硬盘的S.M.A.R.T.是什么?如何看懂它

说道硬盘的S.M.A.R.T.这个既常用然而又陌生的家伙&#xff0c;说真的如果直接看的话有多少个人能看懂这份表&#xff1f;现在我们就要简单的讲解一下NVMe SSD的S.M.A.R.T.信息。 说道硬盘的S.M.A.R.T.这个既常用然而又陌生的家伙&#xff0c;直接说S.M.A.R.T.的话可能很多人都…

ASEMI整流模块MDA110-16参数,MDA110-16规格

编辑-Z ASEMI整流模块MDA110-16参数&#xff1a; 型号&#xff1a;MDA110-16 最大重复峰值反向电压&#xff08;VRRM&#xff09;&#xff1a;1600V 最大RMS电桥输入电压&#xff08;VRMS&#xff09;&#xff1a;1700V 最大平均正向整流输出电流&#xff08;IF&#xff0…

ASEMI整流模块MSAD110-16图片,MSAD110-16体积

编辑-Z ASEMI整流模块MSAD110-16参数&#xff1a; 型号&#xff1a;MSAD110-16 最大重复峰值反向电压&#xff08;VRRM&#xff09;&#xff1a;1600V 最大RMS电桥输入电压&#xff08;VRMS&#xff09;&#xff1a;1700V 最大平均正向整流输出电流&#xff08;IF&#xf…