Java 获取机器码

发布时间:2022-01-28作者:laosun阅读(1347)

Java

    Java 获取机器码

    代码中有部分源码未贴出,但都是普通的,比如MD5加密,用自己的就可以。

    该源码为开源项目中找到的,具体是哪个忘记了,之后自己进行了部分优化

    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    
    import java.lang.management.ManagementFactory;
    import java.lang.management.RuntimeMXBean;
    import java.net.InetAddress;
    import java.net.InterfaceAddress;
    import java.net.NetworkInterface;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    /**
     * 系统工具类
     */
    @Slf4j
    public final class MachineUtils {
    
        /**
         * 运行命令
         *
         * @param cmd  命令
         * @param line 返回第几行结果,0返回所有
         * @return 结果
         */
        public static String runCmd(String cmd, int line) {
            Process process;
            Scanner sc = null;
            StringBuffer sb = new StringBuffer();
            try {
                process = Runtime.getRuntime().exec(cmd);
                process.getOutputStream().close();
                sc = new Scanner(process.getInputStream());
                int i = 0;
                while (sc.hasNextLine()) {
                    i++;
                    String str = sc.nextLine();
                    if (line <= 0) {
                        sb.append(str).append("\r\n");
                    } else if (i == line) {
                        return str.trim();
                    }
                }
                sc.close();
            } catch (Exception e) {
            } finally {
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return sb.toString();
        }
    
        /**
         * 运行cmd命令
         *
         * @param cmd    命令
         * @param substr 关键字
         * @return 包含关键字的行数
         */
        public static String runCmd(String cmd, String substr) {
            Process process;
            Scanner sc = null;
            try {
                process = Runtime.getRuntime().exec(cmd);
                process.getOutputStream().close();
                sc = new Scanner(process.getInputStream());
                // log.info("sc.hasNextLine:{}", sc.hasNext());
                // log.info("sc.hasNextLine:{}", sc.hasNextLine());
                while (sc.hasNextLine()) {
                    String str = sc.nextLine();
                    // log.info("command返回信息:{}", str);
                    if (StringUtils.isNotBlank(str)) {
                        str = str.trim();
                        if (str != null && str.startsWith(substr)) {
                            // log.info("command 提取信息:{}", str);
                            return str.trim();
                        }
                    }
                }
                sc.close();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("执行exec出现异常", e);
            } finally {
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    
        /**
         * 获取mac地址
         *
         * @return mac 列表
         */
        public static String getMacs() {
            List<String> macList = getMacList();
            if (macList != null && macList.size() > 0) {
                return StringUtils.join(macList, ",");
            }
            return null;
        }
    
        /**
         * 获取mac地址
         *
         * @return mac 列表
         */
        public static List<String> getMacList() {
            ArrayList<String> list = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            try {
                java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                while (en.hasMoreElements()) {
                    NetworkInterface iface = en.nextElement();
                    List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
                    for (InterfaceAddress addr : addrs) {
                        InetAddress ip = addr.getAddress();
                        if (ip.isLinkLocalAddress()) {//本地的不要
                            continue;
                        }
                        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
                        if (network == null) {
                            continue;
                        }
    
                        // 先这做,后期优化
                        // TODO
                        if (StringUtils.isNotBlank(network.getName()) && network.getName().startsWith("lo")) {
                            // lo 为本地回环地址,eth0 和 eth4 为 VMware 创建的虚拟地址
                            continue;
                        }
                        if (StringUtils.isNotBlank(network.getName()) && network.getName().startsWith("docker")) {
                            // docker内网地址排除
                            continue;
                        }
                        if (StringUtils.isNotBlank(network.getName()) && (network.getName().startsWith("cni") || network.getName().startsWith("flannel"))) {
                            // docker内网地址排除
                            continue;
                        }
                        if (StringUtils.isNotBlank(network.getName()) && network.getName().startsWith("br")) {
                            // 排除桥接网卡
                            continue;
                        }
    
                        // log.info("ip:{},Network:{}", ip.getHostAddress(), ip.getHostName());
                        // log.info("{}", ip.isLinkLocalAddress());
                        // log.info("{}", ip.isAnyLocalAddress());
                        // log.info("{}", ip.isLoopbackAddress());
                        // log.info("------1");
                        // log.info("{}", ip.isMCGlobal());
                        // log.info("{}", ip.isMCLinkLocal());
                        // log.info("{}", ip.isMCNodeLocal());
                        // log.info("{}", ip.isMCOrgLocal());
                        // log.info("------2");
                        // log.info("{}", ip.isMCSiteLocal());
                        // log.info("{}", ip.isMulticastAddress());
                        // log.info("{}", ip.isSiteLocalAddress());
                        // log.info("------3");
                        // log.info("{}", ip.getCanonicalHostName());
                        // log.info("{}", ip.getHostAddress());
                        // log.info("------4");
                        // log.info("{}", network.supportsMulticast());
                        // log.info("{}", network.getMTU());
                        // log.info("{}", network.getName());
                        // log.info("{}", network.isLoopback());
                        // log.info("------5");
                        // log.info("{}", network.isPointToPoint());
                        // log.info("{}", network.isVirtual());
                        // log.info("{}", network.isUp());
                        // log.info("{}", network.getDisplayName());
                        // log.info("------》》》》》》》");
                        // final NetworkInterface parent = network.getParent();
                        // if (parent != null) {
                        //     log.info("{}", parent.getName());
                        // }
    
                        byte[] mac = network.getHardwareAddress();
                        if (mac == null) {
                            continue;
                        }
    
                        sb.delete(0, sb.length());
                        for (int i = 0; i < mac.length; i++) {
                            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                        if (!list.contains(sb.toString())) {
                            list.add(sb.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
    
        /**
         * 获取cpu序列号
         *
         * @return 序列号
         */
        public static String getCPUSerialNumber() {
            String sysName = System.getProperty("os.name");
            // log.info("系统名称:{}", sysName);
            if (sysName.contains("Windows")) {//win
                String str = runCmd("wmic cpu get ProcessorId", 2);
                return str;
            } else if (sysName.contains("Linux")) {
                String str = runCmd("dmidecode | grep \"ID\"", "ID");
                // log.info("返回信息:{}", str);
                if (str != null) {
                    return str.substring(str.indexOf(":") + 1).trim();
                }
            } else if (sysName.contains("Mac")) {
                String str = runCmd("system_profiler SPHardwareDataType", "Serial Number");
                if (str != null) {
                    return str.substring(str.indexOf(":") + 1).trim();
                }
            }
            return "";
        }
    
        /**
         * 获取硬盘序列号
         *
         * @return 硬盘序列号
         */
        public static String getHardDiskSerialNumber() {
            String sysName = System.getProperty("os.name");
            if (sysName.contains("Windows")) {//win
                String str = runCmd("wmic path win32_physicalmedia get serialnumber", 2);
                return str;
            } else if (sysName.contains("Linux")) {
                // String str = runCmd("dmidecode |grep -A16 \"System Information$\"", "Serial Number");
                String str = runCmd("dmidecode | grep \"Serial Number\"", "Serial Number");
                // log.info("getHardDiskSerialNumber1返回信息:{}", str);
                if (StringUtils.isNotBlank(str) && ": Not Specified".equals(str)) {
                    return str.substring(str.indexOf(":") + 1).trim();
                } else {
                    // str = runCmd("dmidecode |grep -A16 \"System Information$\"", "UUID");
                    str = runCmd("dmidecode | grep \"UUID\"", "UUID");
                    // log.info("getHardDiskSerialNumber2返回信息:{}", str);
                    if (StringUtils.isNotBlank(str)) {
                        return str.substring(str.indexOf(":") + 1).trim();
                    }
                }
            } else if (sysName.contains("Mac")) {
                String str = runCmd("system_profiler SPStorageDataType", "Volume UUID");
                if (str != null) {
                    return str.substring(str.indexOf(":") + 1).trim();
                }
            }
            return "";
        }
    
        /**
         * 获取当前运行进程
         *
         * @author sun
         * @return java.lang.String
         */
        public static String getRuntimeProcess() {
            RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            return runtimeMXBean.getName();
        }
    
        /**
         * 获取当前项目目录
         *
         * @author sun
         * @return java.lang.String
         */
        public static String getRunPath() {
            return PathKit.getRootClassPath();
        }
    
        /**
         * 生成机器码
         *
         * @return 机器码
         */
        public static String makeMarchineCode() {
            String macAddress = getMacList().toString();
            String cpuSerialNumber = getMacList().toString();
            String hardDiskSerialNumber = getMacList().toString();
            // 增加当前项目目录,因为有可能一台机器运行多个,虽然不建议这么做
            String classPath = getRunPath();
    
            log.info("macAddress:{}", macAddress);
            log.info("cpuSerialNumber:{}", cpuSerialNumber);
            log.info("hardDiskSerialNumber:{}", hardDiskSerialNumber);
            log.info("classPath:{}", classPath);
    
            // 组合字符串
            StringBuffer sb = new StringBuffer();
            sb.append(macAddress);
            sb.append(cpuSerialNumber);
            sb.append(hardDiskSerialNumber);
            sb.append(classPath);
    
            // MD5加密
            String code = EncryptionKit.md5Encrypt(sb.toString(), false);
            log.info("生成的机器码:{}", code);
            return code;
        }
    
        public static void main(String[] args) {
            // 1026df16e99f2eef07b383aad6c93476
            log.info(makeMarchineCode());
        }
    
    }


4 +1

版权声明

 Java  源码  开源

 请文明留言

4 条评论