JAVA如何利用Swiger獲取Linux系統電腦配置相關信息


  最近開發java應用程序,涉及到獲取Linux服務器相關配置的問題,特地網上搜尋了下,采用Swiger包可以直接獲取,再次小結一下,以便於以后能方便使用,也便於其他童鞋們學習。

推薦大家參考鏈接:https://www.cnblogs.com/kabi/p/5209315.html

值得注意的問題是:

1.如果是Linux的環境下,要把libsigar-amd64-linux.so文件存放到  lib64下面才能起到作用。

2.如果是Windos環境,將對應的文件存放到jdk的安裝目錄的bin目錄下面即可。

項目中自己封裝的工具類代碼,大家可參考使用:

package com.xuanyin.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import net.sf.json.JSONObject;
/**
 * 此類用戶獲取Linux服務器配置信息
 * @author Administrator
 *
 */
public class LinuxSystem {
    public static  Sigar sigar = new Sigar();  
    /**
     * 功能:獲取Linux系統cpu使用率
     * */
    public static int cpuUsage() {
        try {
            Map<?, ?> map1 = cpuinfo();
            Thread.sleep(500);
            Map<?, ?> map2 = cpuinfo();
            if(map1.size() > 0 && map2.size() > 0){
                long user1 = Long.parseLong(map1.get("user").toString());
                long nice1 = Long.parseLong(map1.get("nice").toString());
                long system1 = Long.parseLong(map1.get("system").toString());
                long idle1 = Long.parseLong(map1.get("idle").toString());

                long user2 = Long.parseLong(map2.get("user").toString());
                long nice2 = Long.parseLong(map2.get("nice").toString());
                long system2 = Long.parseLong(map2.get("system").toString());
                long idle2 = Long.parseLong(map2.get("idle").toString());

                long total1 = user1 + system1 + nice1;
                long total2 = user2 + system2 + nice2;
                float total = total2 - total1;

                long totalIdle1 = user1 + nice1 + system1 + idle1;
                long totalIdle2 = user2 + nice2 + system2 + idle2;
                float totalidle = totalIdle2 - totalIdle1;

                float cpusage = (total / totalidle) * 100;
                return (int) cpusage;
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 功能:CPU使用信息
     * */
    public static Map<?, ?> cpuinfo() {
        InputStreamReader inputs = null;
        BufferedReader buffer = null;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
            buffer = new BufferedReader(inputs);
            String line = "";
            while (true) {
                line = buffer.readLine();
                if (line == null) {
                    break;
                }
                if (line.startsWith("cpu")) {
                    StringTokenizer tokenizer = new StringTokenizer(line);
                    List<String> temp = new ArrayList<String>();
                    while (tokenizer.hasMoreElements()) {
                        String value = tokenizer.nextToken();
                        temp.add(value);
                    }
                    map.put("user", temp.get(1));
                    map.put("nice", temp.get(2));
                    map.put("system", temp.get(3));
                    map.put("idle", temp.get(4));
                    map.put("iowait", temp.get(5));
                    map.put("irq", temp.get(6));
                    map.put("softirq", temp.get(7));
                    map.put("stealstolen", temp.get(8));
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(buffer != null && inputs != null){
                    buffer.close();
                    inputs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return map;
    }

    /**
     * huoqu CPU信息
     * @throws SigarException 
     */
    public static JSONObject getCpuInformation() throws SigarException {
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuList[] = sigar.getCpuPercList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",infos[0].getVendor() + "  " + infos[0].getModel());
        jsonObject.put("sys",CpuPerc.format(cpuList[0].getSys()));
        jsonObject.put("use",CpuPerc.format(cpuList[0].getUser()));
        jsonObject.put("total",CpuPerc.format(cpuList[0].getCombined()));
        //        jsonObject.put("total",CpuPerc.format(cpuUsage()));
        return jsonObject;
    }


    /**
     * 
     * huoqu 系統內存
     * @throws SigarException 
     */
    public static JSONObject  getMemory() throws SigarException {
        Mem mem = sigar.getMem();
        JSONObject jsonObject = new JSONObject();
        int memTotal = (int)Math.ceil((double)mem.getTotal() / (1024L * 1024L ));
        String memFree = String.format("%.1f", (double)mem.getFree() / (1024L * 1024L));
        jsonObject.put("total",memTotal);  //總內存 單位M
        jsonObject.put("use",memTotal-Double.parseDouble(memFree));  //剩余內存 單位M
        jsonObject.put("residue",memFree);  //剩余內存 單位M
        return jsonObject;
    }

    /**
     *  huoqu  硬盤信息
     */
    public static JSONObject getDiskInfromation() {
        JSONObject jsonObject = new JSONObject();
        //獲取硬盤
        Long ypTotal = 0L;
        Long ypfree = 0L;
        try {
            FileSystem fslist[] = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {  
                FileSystem fs = fslist[i];              
                FileSystemUsage usage = null;  
                usage = sigar.getFileSystemUsage(fs.getDirName());  
                switch (fs.getType()) {  
                case 0: // TYPE_UNKNOWN :未知  
                break;  
                case 1: // TYPE_NONE  
                    break;  
                case 2: // TYPE_LOCAL_DISK : 本地硬盤  
                    // 文件系統總大小  
                    ypTotal += usage.getTotal();
                    ypfree += usage.getFree();  
                    break;  
                case 3:// TYPE_NETWORK :網絡  
                    break;  
                case 4:// TYPE_RAM_DISK :閃存  
                    break;  
                case 5:// TYPE_CDROM :光驅  
                    break;  
                case 6:// TYPE_SWAP :頁面交換  
                    break;  
                }      
            }   
            int hdTotal = (int)((double)ypTotal / (1024L));
            String hdfree = String.format("%.1f", (double)ypfree / (1024L));
            jsonObject.put("total",hdTotal);  //總內存 單位M
            jsonObject.put("use",hdTotal-Double.parseDouble(hdfree));  //剩余內存 單位M
            jsonObject.put("residue",hdfree);  //剩余內存 單位M
        } catch (SigarException e1) {
            e1.printStackTrace();
        }  
        return jsonObject;
    }
    /**
     * huoqu 網卡信息
     */
    public static JSONObject getInterCardInformation(int i) {
        JSONObject jsonObject = new JSONObject();
        try {
            String ifNames[] = sigar.getNetInterfaceList();
            jsonObject.put("name", ifNames[i]);//網絡名稱
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(ifNames[i]); 
            jsonObject.put("ip", ifconfig.getAddress());  //ip地址
            jsonObject.put("sonip", ifconfig.getNetmask());  //子網掩碼
            jsonObject.put("cardinformation", ifconfig.getDescription()); //網卡信息
            jsonObject.put("type", ifconfig.getType()); //網卡類型
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(ifNames[i]);
            jsonObject.put("recevie", ifstat.getRxBytes()); //接收到的總字節數
            jsonObject.put("send", ifstat.getTxBytes()); //發送的總字節數
        } catch (SigarException e) {
            e.printStackTrace();
        } 
        return jsonObject;

    }
    /**
     *  設置系統的CPI屬性
     */
    public static JSONObject setSysCpi() {
        JSONObject jsonObject = new JSONObject();
        String exeCmd = exeCmd("lspci  | grep -i vga");
        String exeCmd2 = exeCmd("lspci  | grep -i audio");
        jsonObject.put("showcard", exeCmd.substring(exeCmd.indexOf("controller: ")+12));
        jsonObject.put("voidcard", exeCmd2.substring(exeCmd2.indexOf("controller: ")+12));
        return jsonObject;
    }
    /**
     *    執行linux命令並返回結果
     * @param commandStr
     * @return
     */
    public static String exeCmd(String commandStr) {

        String result = null;
        try {
            String[] cmd = new String[]{"/bin/sh", "-c",commandStr};
            Process ps = Runtime.getRuntime().exec(cmd);
 
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                //執行結果加上回車
                sb.append(line).append("\n");
            }
            result = sb.toString();
 
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM