Java 获取CPU 内存 使用 获取唯一ID

JAVA获取电脑唯一标识,CPU+MAC 【代码】JAVA获取电脑唯一标识,CPU+MAC。 阅读详情
pom.xml



<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.8</version>
        </dependency>

        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>5.6.1</version>
        </dependency>
获取CPU使用率



import java.io.*;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
//https://apidoc.gitee.com/loolly/hutool/cn/hutool/system/oshi/OshiUtil.html#getSystem--




public class Get_cpu {

    /**
     * 获取cpu利用率
     */
    public static void getOsInfo(){
        CpuInfo cpuInfo = OshiUtil.getCpuInfo();
        DecimalFormat format = new DecimalFormat("#.00");
        System.out.println("cpu利用率:" + Double.parseDouble(format.format(100.0D - cpuInfo.getFree())));
    }

    /**
     * 获取内存数据
     */
    public static void getMemoryInfo(){
//        System.out.println("内存总量:" + OshiUtil.getMemory().getTotal()/1024/1024);
//        System.out.println("已用内存:" + (OshiUtil.getMemory().getTotal()-OshiUtil.getMemory().getAvailable())/1024/1024);
        double freemem =((double)(OshiUtil.getMemory().getTotal()-OshiUtil.getMemory().getAvailable())/(double)OshiUtil.getMemory().getTotal())* 100;
        double Memory_Rate=Double.parseDouble(String.format("%.2f",freemem));
        System.out.println("使用百分比:"+Memory_Rate );
    }

    /**
     * 获取硬盘使用量
     */
    public static void getDiskUsed(){
        File win = new File("/");
        if (win.exists()) {
            double freemem =((double)(win.getTotalSpace()-win.getFreeSpace())/ (double)win.getTotalSpace())*100;
            System.out.println("以使用%:" + freemem);
            long total = win.getTotalSpace();
            long freeSpace = win.getFreeSpace();
            System.out.println("磁盘总量:" + total/1024/1024/1024);
            System.out.println("磁盘剩余总量:" + freeSpace/1024/1024/1024);
            System.out.println("磁盘已用总量:" + (total - freeSpace)/1024/1024/1024);
        }
    }



    public static void main(String[] args) {

        getOsInfo();  //获取cpu利用率
        getMemoryInfo();  //获取内存数据
        getDiskUsed();  //获取硬盘使用量

    }
}

获取机器唯一ID


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(" ", ""));
        }

        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();
    }
}

IdWorker生成不重复id IdWorker生成不重复id package entity; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; /** * <p>名称:IdWorker.java</p> * <p>描述:分布式自增长ID</p> * <pre> * Twitter的 Snow 阅读详情

相关推荐

Linux查看应用的CPU内存使用情况

查看应用的CPU内存使用情况,使用jps、ps、top、free、df命令查看,进行性能分析。

新新 2万+

Java 获取计算机唯一标识

该程序,是将当前计算机的 操作系统名前缀 、 主板序列号、 MAC 地址、 CPU 序列号 组合成为JSON 字符串 作为当前计算机唯一标识串。

叁金Coder 1万+

[Unity][安卓]unity获取唯一ID,游客登陆

之前做的时候在网上找了好多有现在整理下一个可以用的 代码段如下 在java中编写 public String GetID(){ String serial = null; String m_szDevIDShort = "35" + Build.BOARD.length()%10+ Build.BRAND.length()...

m0_37602383的博客 5994

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

最近在修改公司licence程序,需要获取到更多的硬件唯一标识,以便加密使用。网上看了很多大神的博客,思路大概整理了一下,根据系统类型分为两种方式:一、windows通过创建vbs脚本,然后使用Runtime.getRuntime().exec()执行脚本,获取序列号等信息。二、LINUXlinux系统其实差不多,同样使用Runtime.getRuntime().exec()执行linux命令,获...

ChenDaShu大叔的博客 2万+

java支持跨平台获取cpuid、主板id、硬盘id、mac地址 (兼容windows、Linux)

windows: ? package cn.net.comsys.helper.system.info; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader

chen_xiaowei123的专栏 2518

CocosCreator获取设备ID唯一标识符

获取设备信息等操作, 要先到java层去. 在这个文件里面添加代码,用于获取需要的设备信息: 路径:“bulid\jsb-default\frameworks\cocos2d-x\cocos\platform\android\java\src\org\cocos2dx\lib\Cocos2dxActivity.java” 在这个文件里面获取权限: 路径:“bulid\jsb-default\frameworks\runtime-src\proj.android-studio\app\AndroidManif

书生的博客 5971

Linux下使用java获取cpu内存使用

原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU内存情况,通过Runtime类的exec()方法执行命令"top”,获取"top"的输出,从而得到CPU内存使用情况。 使用top命令获取系统信息: top -b -n -1...

as403045314的博客 1922

android获取设备唯一ID方法

1、方案一IMEI IMEI(International Mobile Equipment Identity)是国际移动设备识别码的缩写,由15-17位数字组成,与手机是一一对应的关系,该码是全球唯一的,并且永远不会改变。 2、不同版本获取IEMI的方式 在Android 8.0(API Level 26)以下,可以通过TelephonyManager的getDeviceId()方法获取到设备的IMEI码(其实这里的说法不准确,该方法是会根据手机设备的制式(GSM或CDMA)返回...

suwenlai的博客 3万+

Java根据时间戳生产ID_java唯一字符串ID生成方案详解

工作中经常会有生成唯一字符串的需求。通常最容易想到的是UUID。UUID唯一性毋庸置疑,但是32位的长度也容易让人退避三舍。也曾经想过参考《短网址生成方案》来生成一串ID,但是试验了一下发现唯一性不太好。最终采用的方案是时钟方案,简单来说就是用当前时间戳做唯一ID。采用时间戳做ID,秒或毫秒都容易产生重复,换成纳秒在单节点上就没问题了。参考百度百科关于纳秒的描述就能清楚为什么纳秒级别的时间戳不会...

weixin_31572175的博客 5840

java获取进程id 读写内存_java 获取进程ID 物理内存 cpu使用百分比(linux环境)

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.math.BigDecimal;import org.apache.log4j.Logger;import sun.management.ManagementFactory;import com....

weixin_28702613的博客 370

使用java获取进程内存使用情况

为什么80%的码农都做不了架构师?>>> ...

weixin_34391445的博客 3849

linux——CPU使用率、内存使用率、磁盘使用率等详解

1:CPU使用率 可参考linux系统查看CPU使用率的命令 常用命令:top top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器。 [root@izwz94b8tt3jlf3ne0ymp3z ~]# top top - 09:27:04 up 49 days, 23:46, 8 users, load average: 0.68, 0.72, 0.71 Tasks: 642 total, 1 running, 641 sleepi

weixin_43928833的博客 2万+

java生成唯一字符串_java唯一字符串ID生成方案详解

工作中经常会有生成唯一字符串的需求。通常最容易想到的是UUID。UUID唯一性毋庸置疑,但是32位的长度也容易让人退避三舍。也曾经想过参考《短网址生成方案》来生成一串ID,但是试验了一下发现唯一性不太好。最终采用的方案是时钟方案,简单来说就是用当前时间戳做唯一ID。采用时间戳做ID,秒或毫秒都容易产生重复,换成纳秒在单节点上就没问题了。参考百度百科关于纳秒的描述就能清楚为什么纳秒级别的时间戳不会...

weixin_34205994的博客 5726

java 获取进程ID 物理内存 cpu使用百分比(linux环境)

http://hhhk.iteye.com/blog/1197434 java 获取进程ID Java代码   import java.io.BufferedReader;   import java.io.IOException;   import java.io.InputStreamReader;   import java.math.BigDecim

qiezikuaichuan的专栏 3945

java获取进程id 读写内存_java获取系统信息(CPU内存,硬盘,进程)的相关方法...

一、这是一个获取相关信息的简单的方法import java.io.*;importcom.sun.management.OperatingSystemMXBean;import sun.management.ManagementFactory;publicclass Tst{publicstatic String pt="D:\\abc.txt";publicTst(){}publicstatic...

weixin_39744408的博客 439

linux cpu id是什么意思,linux获取cpu id和disk id

// 获得CPU IDpublic static final String CPU_ID_CMD = "dmidecode -t 4 | grep ID |sort -u |awk -F': ' '{print $2}'";// 获得磁盘IDpublic static final String DISK_ID_CMD = "fdisk -l |grep \"Disk identifier\" |a...

weixin_36409041的博客 848

java进程CPU使用率高排查

近期java应用,CPU使用率一直很高,经常达到100%,通过以下步骤完美解决,分享一下。 方法一: 1.jps 获取Java进程的PID。 2.jstack pid >> java.txt 导出CPU占用高进程的线程栈。 3.top -H -p PID 查看对应进程的哪个线程占用CPU过高。 4.echo “obase=16; PID” | bc 将线程的PID转换为16进制,大写转换为小写。 5.在第二步导出的Java.txt中查找转换成为16进制的线程PID。找到对应的线程栈。 6.分

m0_67505608的博客 5010

java线程id获得堆栈_CPU获取其线程ID然后分析

一、具体步骤shift+p 按照cpu排序shift+m按照内存排序1、查看进程下所有线程 top -H -p pid2、将十进制数换成16进制:print "%x/n" 线程id3、查看进程下的线程正在执行的方法: jstack pid|grep 0X70d4以我们最近出现的一个实际故障为例,介绍怎么定位和解决这类问题。clip_image002根据top命令,发现PID为28555的J...

weixin_42512096的博客 551
上一篇: java获取系统CPU和内存使用率的三种方法
下一篇: JAVA //七牛云上传//阿里云上传//发送邮件//短信验证码//钉钉消息
QQ7650371
博客等级 码龄11年 159粉丝 192原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值