Java 统计linux各种资源
0
/** * 获取带宽上传下载速度 * @return */ public String getNetWorkSpeed() { boolean result = false; String detailInfo = ""; DecimalFormat df = new DecimalFormat("0.00"); String dl = ""; String ul = ""; System.out.println("开始收集网络带宽使用率"); Process pro1,pro2; Runtime r = Runtime.getRuntime(); try { String command = "cat /proc/net/dev"; //第一次采集流量数据 long startTime = System.currentTimeMillis(); pro1 = r.exec(command); BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream())); String line = null; long inSize1 = 0, outSize1 = 0; while((line=in1.readLine()) != null){ line = line.trim(); if(line.startsWith("eth0")){ System.out.println(line); String[] temp = line.split("\\s+"); inSize1 = Long.parseLong(temp[1]); //Receive bytes,单位为Byte outSize1 = Long.parseLong(temp[9]); //Transmit bytes,单位为Byte break; } } in1.close(); pro1.destroy(); try { Thread.sleep(1000); } catch (InterruptedException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println("NetUsage休眠时发生InterruptedException. " + e.getMessage()); System.out.println(sw.toString()); } //第二次采集流量数据 long endTime = System.currentTimeMillis(); pro2 = r.exec(command); BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream())); long inSize2 = 0 ,outSize2 = 0; while((line=in2.readLine()) != null){ line = line.trim(); if(line.startsWith("eth0")){ System.out.println(line); String[] temp = line.split("\\s+"); inSize2 = Long.parseLong(temp[1]); outSize2 = Long.parseLong(temp[9]); break; } } //cal dl speed float interval = (float)(endTime - startTime)/1000; float currentDlSpeed = (float) ((float)(inSize2 - inSize1)/1024/interval); float currentUlSpeed = (float) ((float)(outSize2 - outSize1)/1024/interval); if((float)(currentDlSpeed/1024) >= 1){ currentDlSpeed = (float)(currentDlSpeed/1024); dl = df.format(currentDlSpeed) + "Mb/s"; }else{ dl = df.format(currentDlSpeed) + "Kb/s"; } if((float)(currentUlSpeed/1024) >= 1){ currentUlSpeed = (float)(currentUlSpeed/1024); ul = df.format(currentUlSpeed) + "Mb/s"; }else{ ul = df.format(currentUlSpeed) + "Kb/s"; } result = true; in2.close(); pro2.destroy(); } catch (Exception e) { e.printStackTrace(); detailInfo = e.getMessage(); } return "{\"result\":\""+result+"\",\"detailInfo\":\""+detailInfo+"\",\"dl\":\""+dl+"\",\"ul\":\""+ul+"\"}"; }
/** * 功能:内存使用率 * */ public float memoryUsage() { 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()); float usage = (float) (memused - buffers - cached) / memTotal; return usage; } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); inputs.close(); } catch (Exception e2) { e2.printStackTrace(); } } return 0; }
/** * 获取分区的使用占用率 * @param path * @return */ public float getPatitionUsage(String path){ File f = new File(path); long total = f.getTotalSpace(); long free = f.getFreeSpace(); long used = total - free; float usage = (float)used/total; return usage; }
/** * 获取磁盘IO使用率 * @return */ public float getHdIOpPercent() { System.out.println("开始收集磁盘IO使用率"); float ioUsage = 0.0f; Process pro = null; Runtime r = Runtime.getRuntime(); try { String command = "iostat -d -x"; pro = r.exec(command); BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream())); String line = null; int count = 0; while((line=in.readLine()) != null){ if(++count >= 4){ // System.out.println(line); String[] temp = line.split("\\s+"); if(temp.length > 1){ float util = Float.parseFloat(temp[temp.length-1]); ioUsage = (ioUsage>util)?ioUsage:util; } } } if(ioUsage > 0){ System.out.println("本节点磁盘IO使用率为: " + ioUsage); ioUsage /= 100; } in.close(); pro.destroy(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println("IoUsage发生InstantiationException. " + e.getMessage()); System.out.println(sw.toString()); } return ioUsage; }
package getnetworkinfo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; /** * 采集网络带宽使用率 */ public class NetUsage { private static NetUsage INSTANCE = new NetUsage(); private final static float TotalBandwidth = 1000; //网口带宽,Mbps private NetUsage(){ } public static NetUsage getInstance(){ return INSTANCE; } /** * @Purpose:采集网络带宽使用率 * @param args * @return float,网络带宽使用率,小于1 */ // @Override public float get() { System.out.println("Start collecting network bandwidth usage"); float netUsage = 0.0f; Process pro1,pro2; Runtime r = Runtime.getRuntime(); try { String command = "cat /proc/net/dev"; //第一次采集流量数据 long startTime = System.currentTimeMillis(); pro1 = r.exec(command); BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream())); String line = null; long inSize1 = 0, outSize1 = 0; while((line=in1.readLine()) != null){ line = line.trim(); if(line.startsWith("eth0")){ System.out.println(line); String[] temp = line.split("\\s+"); inSize1 = Long.parseLong(temp[0].substring(5)); //Receive bytes,单位为Byte outSize1 = Long.parseLong(temp[8]); //Transmit bytes,单位为Byte break; } } in1.close(); pro1.destroy(); try { Thread.sleep(1000); } catch (InterruptedException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.err.println("NetUsage has InterruptedException when sleeping. " + e.getMessage()); System.err.println(sw.toString()); } //第二次采集流量数据 long endTime = System.currentTimeMillis(); pro2 = r.exec(command); BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream())); long inSize2 = 0 ,outSize2 = 0; while((line=in2.readLine()) != null){ line = line.trim(); if(line.startsWith("eth0")){ System.out.println(line); String[] temp = line.split("\\s+"); inSize2 = Long.parseLong(temp[0].substring(5)); outSize2 = Long.parseLong(temp[8]); break; } } if(inSize1 != 0 && outSize1 !=0 && inSize2 != 0 && outSize2 !=0){ float interval = (float)(endTime - startTime)/1000; //带宽利用率:单位时间内 bytes的差除以网络最大带宽 //网口传输速度,单位为bps float curRate = (float)(inSize2 - inSize1 + outSize2 - outSize1)*8/(TotalBandwidth*1000*interval); float f = curRate/TotalBandwidth; // netUsage = curRate/TotalBandwidth; netUsage = (float)(Math.round(f*10000))/100; System.out.println("The network port speed of this node is: " + curRate + "Mbps"); System.out.println("The network bandwidth utilization rate of this node is: " + netUsage+"%"); } in2.close(); pro2.destroy(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.err.println("NetUsage has InstantiationException. " + e.getMessage()); System.err.println(sw.toString()); } return netUsage; } /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { while(true){ System.out.println(NetUsage.getInstance().get()); Thread.sleep(5000); } } }
/** * 获取MAC * * @return */ public String getMac() { String result = ""; try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface network = networkInterfaces.nextElement(); System.out.println("network : " + network); byte[] mac = network.getHardwareAddress(); if (mac == null) { System.out.println("null mac"); } else { System.out.print("MAC address : "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); } result = sb.toString(); System.out.println(sb.toString()); break; } } } catch (SocketException e) { e.printStackTrace(); } return result; }