使用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 map = new HashMap();
            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 IFaces = null;
        try {
            IFaces = NetworkInterface.getNetworkInterfaces();
            while (IFaces.hasMoreElements()) {
                NetworkInterface fInterface = IFaces.nextElement();
                if (!fInterface.isVirtual() && !fInterface.isLoopback() && fInterface.isUp()) {
                    Enumeration 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

你可能感兴趣的:(使用Sigar获取服务器内存、IP、CPU、IO、MAC地址、操作系统等信息...)