最近开发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; } }
个人学习随笔,若是帮助到您,请给个推荐,或者评论一下下,谢谢了哟。若有不懂之处,请联系QQ:351094262(验证信息:博客园),原创不易,转载请标明出处!