使用Sigar获取服务器内存、IP、CPU、IO、MAC地址、操作系统等信息...

sigar linux 文件和windows文件和sigar的jar包

链接: https://pan.baidu.com/s/1bGrupzmaOAjLEUE0gp6DmA 提取码: gj31

工具类

import com.sun.management.OperatingSystemMXBean;
import org.hyperic.sigar.*;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class MachineUtils {

    private static String osName = System.getProperty("os.name");
    /***
     * 获取cpu平均值使用率
     */
    public static Double getCPURate() {
        Double CPURate = 0.0;
        Double CPURate1 = 0.0;
        try {
            Sigar sigar = new Sigar();
            CpuInfo infos[] = new CpuInfo[0];
            infos = sigar.getCpuInfoList();
            CpuPerc cpuList[] = null;
            cpuList = sigar.getCpuPercList();
            for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
                CpuInfo info = infos[i];
                CPURate += cpuList[i].getCombined();
            }
            CPURate1 = CPURate / infos.length;
        } catch (SigarException e) {
            e.printStackTrace();
        }
        CPURate1 = (double) Math.round(CPURate1 * 100);
        return CPURate1;
    }

    /***
     *  获取内存使用率
     */
    public static String Memory(){
        if (osName.toLowerCase().contains("windows") || osName.toLowerCase().contains("win")) {
            String memory = getMemery();
            return memory;
        } else {
            String memory = getMemUsage()+"";
            return memory;
        }
    }
    /**
     * 获取windows内存使用率
     */
    public static String getMemery() {
        String format = "";
        try {
            DecimalFormat df = new DecimalFormat("#.00");
            Sigar sigar = new Sigar();
            Mem mem = sigar.getMem();
            float total = mem.getTotal() / 1024L;
            float used = mem.getUsed() / 1024L;
            format = df.format((used/total)*100);
            return  format;
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return  format;
    }
    /***
     * 获取linux内存使用率
     */
    public static String getMemUsage() {
            Map<String, Object> map = new HashMap<String, Object>();
            InputStreamReader inputs = null;
            BufferedReader buffer = null;
            try {
                inputs = new InputStreamReader(new FileInputStream("/proc/meminfo"));
                buffer = new BufferedReader(inputs);
                String line = "";
                while (true) {
                    line = buffer.readLine();
                    if (line == null)
                        break;
                    int beginIndex = 0;
                    int endIndex = line.indexOf(":");
                    if (endIndex != -1) {
                        String key = line.substring(beginIndex, endIndex);
                        beginIndex = endIndex + 1;
                        endIndex = line.length();
                        String memory = line.substring(beginIndex, endIndex);
                        String value = memory.replace("kB", "").trim();
                        map.put(key, value);
                    }
                }
                long memTotal = Long.parseLong(map.get("MemTotal").toString());
                long memFree = Long.parseLong(map.get("MemFree").toString());
                long memused = memTotal - memFree;
                long buffers = Long.parseLong(map.get("Buffers").toString());
                long cached = Long.parseLong(map.get("Cached").toString());
                double usage = (double) (memused-buffers-cached) / memTotal * 100;
                DecimalFormat df = new DecimalFormat("#.00");
                String format = df.format(usage);
                return format;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    buffer.close();
                    inputs.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        return "0";
    }
/**
 * 获取磁盘Read吞吐量
 *
 * @return
 */
public static long getTotalDiskReadByte() {
    Sigar sigar = new Sigar();
    long totalByte = 0;
    try {
        FileSystem[] fslist = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            if (fslist[i].getType() == 2) {
                FileSystemUsage usage = sigar.getFileSystemUsage(fslist[i].getDirName());
                totalByte += usage.getDiskReadBytes();
            }
        }
    } catch (SigarException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return totalByte;
}
/**
 * 获取磁盘Write吞吐量
 *
 * @return
 */
public static long getTotalDiskWriteByte() {
    Sigar sigar = new Sigar();
    long totalByte = 0;
    try {
        FileSystem[] fslist = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            if (fslist[i].getType() == 2) {
                FileSystemUsage usage = sigar.getFileSystemUsage(fslist[i].getDirName());
                totalByte += usage.getDiskWriteBytes();
            }
        }
    } catch (SigarException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return totalByte;
}    
/**
     * @Description: 系统上传下载总量
     * @Date:
     */
    public static String[] getOBytes() {
        Sigar sigar = new Sigar();
        String ifNames[] = null;
        String[] arr = new String[2];

        long txbyte = 0;
        long rxbyte = 0;
        try {
            //获取网卡名称
            ifNames = sigar.getNetInterfaceList();
            for (int i = 0; i < ifNames.length; i++) {
                String name = ifNames[i];
                NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);//fasong
                long txBytes = ifstat.getTxBytes();
                long rxBytes = ifstat.getRxBytes();
                if (txBytes != 0 && !"lo".equals(name)) {
                    txbyte += txBytes;
                    rxbyte += rxBytes;

                }
            }
            arr[0] = bytes2kb(rxbyte);
            arr[1] = bytes2kb(txbyte);
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return arr;
    }

    //long byte转Kb
    public static String bytes2kb(long bytes) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format((double) bytes / 1024);
    }

    public static long getAllDiskReadSpeed() {
        Sigar sigar = new Sigar();
        FileSystem fslist[] = new FileSystem[0];
        long DiskReads = 0;
        try {
            fslist = sigar.getFileSystemList();

            for (int i = 0; i < fslist.length; i++) {
                FileSystem fs = fslist[i];
                FileSystemUsage usage = null;
                usage = sigar.getFileSystemUsage(fs.getDirName());
                DiskReads += usage.getDiskReads();
            }
        } catch (SigarException e) {
            e.printStackTrace();
        }

        return DiskReads / fslist.length;
    }

    public static long getAllDiskWriteSpeed() {
        Sigar sigar = new Sigar();
        long DiskWrites = 0;
        FileSystem fslist[] = new FileSystem[0];
        try {
            fslist = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {
                FileSystem fs = fslist[i];
                FileSystemUsage usage = null;
                usage = sigar.getFileSystemUsage(fs.getDirName());
                DiskWrites += usage.getDiskWrites();
            }
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return DiskWrites / fslist.length;
    }

    public static String CompIp() {
        String ip = "";
        Enumeration<NetworkInterface> IFaces = null;
        try {
            IFaces = NetworkInterface.getNetworkInterfaces();
            while (IFaces.hasMoreElements()) {
                NetworkInterface fInterface = IFaces.nextElement();
                if (!fInterface.isVirtual() && !fInterface.isLoopback() && fInterface.isUp()) {
                    Enumeration<InetAddress> adds = fInterface.getInetAddresses();
                    while (adds.hasMoreElements()) {
                        InetAddress address = adds.nextElement();
                        byte[] bs = address.getAddress();
                        if (bs.length == 4)
                            ip += address.getHostAddress() + ",";
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip.substring(0, ip.length() - 1);
    }

    public static void main(String[] args){
    }
}
float R = 0.00f;
float T = 0.00f;
float write = 0.00f;
float read = 0.00f;
Monitor monitor = new Monitor();
String updataTime = DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss");
monitor.setCPUCOL((int) Math.round(MachineUtils.getCPURate()));//CPU
monitor.setMemoryCOL(Float.parseFloat(MachineUtils.Memory()));//内存
if (readSpeed != 0) {
    float as = (MachineUtils.getTotalDiskReadByte() - readSpeed) / 5;
    BigDecimal b = new BigDecimal(as /1024 /1024);
    read = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
}
if (writeSpeed != 0) {
    float as = (MachineUtils.getTotalDiskWriteByte() - writeSpeed) / 5;
    BigDecimal b = new BigDecimal(as /1024 /1024);
    write = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
}

monitor.setTotalReadSpeedCOL(read);//所有磁盘读取速度
monitor.setTotalWriteSpeedCOL(write);//所有磁盘写入速度
String[] oBytes = MachineUtils.getOBytes();
float down = Float.parseFloat(oBytes[0]);
float up = Float.parseFloat(oBytes[1]);
if (lastRBytes != 0) {
    float as = (down - lastRBytes) / 5;
    R = (float) (Math.round(as * 100)) / 100;//*100   然后   /100 是保留两位
}
if (lastTBytes != 0) {
    float as = (up - lastTBytes) / 5;
    T = (float) (Math.round(as * 100)) / 100;
}
lastRBytes = down;//下载
lastTBytes = up;//上传
readSpeed = MachineUtils.getTotalDiskReadByte();
writeSpeed = MachineUtils.getTotalDiskWriteByte();

博客链接

https://blog.csdn.net/wudiazu/article/details/73829324

sigar官网地址:

https://sourceforge.net/projects/sigar/

转载于:https://my.oschina.net/u/3774949/blog/3064706

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sigar 是一个跨平台的系统信息收集库,可以获取系统的 CPU内存、磁盘、网络等信息。以下是获取系统信息的示例代码: ```java import org.hyperic.sigar.*; public class SigarDemo { public static void main(String[] args) throws SigarException { Sigar sigar = new Sigar(); System.out.println("CPU信息:"); CpuInfo[] cpuInfos = sigar.getCpuInfoList(); for (CpuInfo cpuInfo : cpuInfos) { System.out.println("CPU型号:" + cpuInfo.getModel()); System.out.println("CPU频率:" + cpuInfo.getMhz() + "MHz"); System.out.println("CPU核数:" + cpuInfo.getTotalCores()); } System.out.println("内存信息:"); Mem mem = sigar.getMem(); System.out.println("总内存:" + mem.getTotal() / 1024 / 1024 + "MB"); System.out.println("已用内存:" + mem.getUsed() / 1024 / 1024 + "MB"); System.out.println("剩余内存:" + mem.getFree() / 1024 / 1024 + "MB"); System.out.println("磁盘信息:"); FileSystem[] fileSystems = sigar.getFileSystemList(); for (FileSystem fileSystem : fileSystems) { System.out.println("盘符:" + fileSystem.getDirName()); System.out.println("盘符类型:" + fileSystem.getTypeName()); FileSystemUsage usage = sigar.getFileSystemUsage(fileSystem.getDirName()); System.out.println("总大小:" + usage.getTotal() / 1024 / 1024 + "MB"); System.out.println("已用大小:" + usage.getUsed() / 1024 / 1024 + "MB"); System.out.println("剩余大小:" + usage.getFree() / 1024 / 1024 + "MB"); } System.out.println("网络信息:"); NetInterfaceConfig[] netConfigs = sigar.getNetInterfaceConfigList(); for (NetInterfaceConfig netConfig : netConfigs) { System.out.println("网络设备名:" + netConfig.getName()); System.out.println("IP地址:" + netConfig.getAddress()); System.out.println("子网掩码:" + netConfig.getNetmask()); } } } ``` 注意:需要引入 sigar.jar 和 sigar-amd64-winnt.dll(或其它平台对应的库文件)。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值