获取cpu序列号

获取cpu序列号

/*
 * 文 件 名: ExcCommand.java 版 权: Unis Cloud Information Technology Co., Ltd.
 * Copyright 2017, All rights reserved 描 述: <描述> 修 改 人: Administrator 修改时间:
 * 2017年11月14日 跟踪单号: <跟踪单号> 修改单号: <修改单号> 修改内容: <修改内容>
 */
package com.hubin.cpunum;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Scanner;

public class ExcCommand {
    public static boolean isRegister = false;
    
    // 机器序列号
    private static String machineCode;
    
    /**
     * @return 返回 machineCode
     */
    public static String getMachineCode() {
        if (machineCode == null) {
            machineCode = getSn();
        }
        return machineCode;
    }
    
    /**
     * @param 对machineCode进行赋值
     */
    public static void setMachineCode(String machineCode) {
        ExcCommand.machineCode = machineCode;
    }
    
    public static String getSn() {
        String cid = "EEEE";
        String hid = "EEEE";
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.indexOf("win") > -1) {// windows系统
            cid = getCPUSerialInWindows();
            hid = getHardDiskSN("c");
        }
        else {// Linux系统
            cid = getCPUSerial();
            hid = getMBId();
        }
        if (hid.length() < 4) {
            hid = "EEEE";
        }
        /*
         * String mac = "EEEE"; try { String allMac = getMACAddress();
         * System.out.println("mac:"+allMac); mac = allMac.substring(8); } catch
         * (Exception e) { e.printStackTrace(); } //
         */
        String sn = cid + hid.substring(hid.length() - 4);
        sn = sn.substring(0, 4) + "-" + sn.substring(4, 8) + "-" + sn.substring(8, 12) + "-" + sn.substring(12);
        return sn;
    }
    
    /**
     * 获取CPU序列号,windows系统
     * 
     * @return
     */
    public static String getCPUSerialInWindows() {
        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();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo \"" + file.getPath() + "\"");
            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被读取";
        }
        else {
            result = result.trim();
        }
        return result;
    }
    
    /**
     * 获取CUP序列号 linux系统
     * 
     * @return [参数说明]
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String getCPUSerial() {
        String osName = System.getProperty("os.name").toLowerCase();
        String result[] = new String[2];
        String para[] = new String[3];
        ArrayList<String> param = new ArrayList<String>();
        String cpuid = null;
        System.out.println("osName:" + osName);
        try {
            if (osName.indexOf("windows 9") > -1) {
                param.add("command.com");
                // ignore win9
                /*
                 * param.add("/c"); param.add("wmic cpu get ProcessorId");
                 * result = ExcCommand.exec((String[])param.toArray()); //
                 */
            }
            else if (osName.indexOf("win") > -1) {
                param.add("cmd.exe");
                param.add("/c");
                param.add("wmic cpu get ProcessorId");
                result = exec(param.toArray(para));
                if (0 < result[1].length()) {
                    System.out.println("error info:---------------\r\n" + result[1]);
                }
                result[0] = result[0].trim();
                cpuid = result[0].substring(result[0].lastIndexOf('\n') + 1);
            }
            else {
                // Linux,Unix
                param.add("/bin/sh");
                param.add("-c");
                param.add("dmidecode -t processor |grep 'ID'");
                result = exec(param.toArray(para));
                if (0 < result[1].length()) {
                    System.out.println("error info:---------------\r\n" + result[1]);
                }
                cpuid = result[0].substring(result[0].indexOf(' ') + 1, result[0].indexOf('\n'));
                cpuid = cpuid.replace(" ", "");
            }
        }
        catch (Throwable e) {
            e.printStackTrace();
            return "";
        }
        // if (16 == cpuid.length()) {
        // cpuid = cpuid.substring(0, 4) + "-" + cpuid.substring(4, 8) + "-" +
        // cpuid.substring(8, 12) + "-"
        // + cpuid.substring(12);
        // }
        return cpuid;
    }
    
    /**
     * 获取硬盘序列号,windows系统
     * 
     * @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();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo \"" + file.getPath() + "\"");
            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.printStackTrace();
        }
        return result.trim();
    }
    
    // 获取linux系统的主板id
    public static String getMBId() {
        String result[] = new String[2];
        String para[] = new String[3];
        ArrayList<String> param = new ArrayList<String>();
        String mbid = "EEEE";
        param.add("/bin/sh");
        param.add("-c");
        param.add("dmidecode |grep 'Serial Number'");
        try {
            result = exec(param.toArray(para));
            if (0 < result[1].length()) {
                System.out.println("error info:---------------\r\n" + result[1]);
            }
            String[] sn = result[0].split("Serial Number: ");
            String ms;
            for (int i = 0; i < sn.length; i++) {
                ms = sn[i].trim();
                if ("Not Specified".equalsIgnoreCase(ms)) {
                    continue;
                }
                if (10 == ms.length()) {
                    mbid = ms;
                    break;
                }
            }
        }
        catch (Throwable e) {
            e.printStackTrace();
        }
        return mbid;
    }
    
    /**
     * <一句话功能简述>获取CUP序列号 <功能详细描述>
     * 
     * @return [参数说明]
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String getCPU() {
        Process process;
        String serial = null;
        try {
            process = Runtime.getRuntime().exec(new String[] { "wmic", "cpu", "get", "ProcessorId" });
            process.getOutputStream().close();
            Scanner sc = new Scanner(process.getInputStream());
            String property = sc.next();
            serial = sc.next();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return serial;
    }
    
    public static String getLocalMACAddress() throws Exception {
        InetAddress ia = InetAddress.getLocalHost();// 获取本地IP对象
        // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // 下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer();
        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地址并返回
        return sb.toString().toUpperCase();
    }
    
    // 获取MAC地址的方法
    public static String getMACAddress() throws Exception {
        InetAddress ia = InetAddress.getLocalHost();// 获取本地IP对象
        // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        String macRes = "EEEEEEEEEEEE";
        // 下面代码是把mac地址拼装成String
        StringBuffer sb;
        while (nis.hasMoreElements()) {
            byte[] mac = nis.nextElement().getHardwareAddress();// NetworkInterface.getByInetAddress(ia)
            if (null != mac && 0 < mac.length) {
                sb = new StringBuffer();
                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);
                }
                macRes = sb.toString().toUpperCase();
                // System.out.println("get MAC:" + macRes);
                // return sb.toString().toUpperCase();
            }
        }
        return macRes;
    }
    
    /**
     * 返回命令执行结果信息串
     * 
     * @param command 要执行的命令
     * @return 第一个为标准信息,第二个为错误信息
     * @throws Throwable String[]
     */
    public static String[] exec(String[] command) throws Throwable {
        Process process = null;
        Runtime runtime = Runtime.getRuntime();
        // Linux,Unix
        process = runtime.exec(command);
        // 存储返回结果,第一个为标准信息,第二个为错误信息
        String result[] = new String[2];
        ReadThread inputReadThread = new ReadThread(process.getInputStream());
        ReadThread errReadThread = new ReadThread(process.getErrorStream());
        inputReadThread.start();
        errReadThread.start();
        // 确保标准与错误流都读完时才向外界返回执行结果
        while (true) {
            if (inputReadThread.flag && errReadThread.flag) {
                break;
            }
            else {
                Thread.sleep(200);
            }
        }
        result[0] = inputReadThread.getResult();
        result[1] = errReadThread.getResult();
        return result;
    }
    
    public static void main(String args[]) throws Throwable {
        System.out.println(getSn());
    }
    
    /*
     * 标准流与错误流读取线程
     */
    private static class ReadThread extends Thread {
        private InputStream is;
        
        private ArrayList result = new ArrayList();
        
        public boolean flag;// 流是否读取完毕
        
        public ReadThread(InputStream is) {
            this.is = is;
        }
        
        // 获取命令执行后输出信息,如果没有则返回空""字符串
        protected String getResult() {
            byte[] byteArr = new byte[result.size()];
            for (int i = 0; i < result.size(); i++) {
                byteArr[i] = ((Byte) result.get(i)).byteValue();
            }
            return new String(byteArr);
        }
        
        public void run() {
            try {
                int readInt = is.read();
                while (readInt != -1) {
                    result.add(Byte.valueOf(String.valueOf((byte) readInt)));
                    readInt = is.read();
                }
                flag = true;// 流已读完
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值