Linux Java 获取CPU使用率,内存使用率,磁盘IO,网络带宽使用率等等


  1. <pre name= "code" class= "java"> /**
  2. * 获取带宽上传下载速度
  3. * @return
  4. */
  5. public String getNetWorkSpeed() {
  6. boolean result = false;
  7. String detailInfo = "";
  8. DecimalFormat df = new DecimalFormat( "0.00");
  9. String dl = "";
  10. String ul = "";
  11. System.out.println( "开始收集网络带宽使用率");
  12. Process pro1,pro2;
  13. Runtime r = Runtime.getRuntime();
  14. try {
  15. String command = "cat /proc/net/dev";
  16. //第一次采集流量数据
  17. long startTime = System.currentTimeMillis();
  18. pro1 = r.exec(command);
  19. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  20. String line = null;
  21. long inSize1 = 0, outSize1 = 0;
  22. while((line=in1.readLine()) != null){
  23. line = line.trim();
  24. if(line.startsWith( "eth0")){
  25. System.out.println(line);
  26. String[] temp = line.split( "\\s+");
  27. inSize1 = Long.parseLong(temp[ 1]); //Receive bytes,单位为Byte
  28. outSize1 = Long.parseLong(temp[ 9]); //Transmit bytes,单位为Byte
  29. break;
  30. }
  31. }
  32. in1.close();
  33. pro1.destroy();
  34. try {
  35. Thread.sleep( 1000);
  36. } catch (InterruptedException e) {
  37. StringWriter sw = new StringWriter();
  38. e.printStackTrace( new PrintWriter(sw));
  39. System.out.println( "NetUsage休眠时发生InterruptedException. " + e.getMessage());
  40. System.out.println(sw.toString());
  41. }
  42. //第二次采集流量数据
  43. long endTime = System.currentTimeMillis();
  44. pro2 = r.exec(command);
  45. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  46. long inSize2 = 0 ,outSize2 = 0;
  47. while((line=in2.readLine()) != null){
  48. line = line.trim();
  49. if(line.startsWith( "eth0")){
  50. System.out.println(line);
  51. String[] temp = line.split( "\\s+");
  52. inSize2 = Long.parseLong(temp[ 1]);
  53. outSize2 = Long.parseLong(temp[ 9]);
  54. break;
  55. }
  56. }
  57. //cal dl speed
  58. float interval = ( float)(endTime - startTime)/ 1000;
  59. float currentDlSpeed = ( float) (( float)(inSize2 - inSize1)/ 1024/interval);
  60. float currentUlSpeed = ( float) (( float)(outSize2 - outSize1)/ 1024/interval);
  61. if(( float)(currentDlSpeed/ 1024) >= 1){
  62. currentDlSpeed = ( float)(currentDlSpeed/ 1024);
  63. dl = df.format(currentDlSpeed) + "Mb/s";
  64. } else{
  65. dl = df.format(currentDlSpeed) + "Kb/s";
  66. }
  67. if(( float)(currentUlSpeed/ 1024) >= 1){
  68. currentUlSpeed = ( float)(currentUlSpeed/ 1024);
  69. ul = df.format(currentUlSpeed) + "Mb/s";
  70. } else{
  71. ul = df.format(currentUlSpeed) + "Kb/s";
  72. }
  73. result = true;
  74. in2.close();
  75. pro2.destroy();
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. detailInfo = e.getMessage();
  79. }
  80. return "{\"result\":\""+result+ "\",\"detailInfo\":\""+detailInfo+ "\",\"dl\":\""+dl+ "\",\"ul\":\""+ul+ "\"}";
  81. }


 
 
  1. /**
  2. * 功能:内存使用率
  3. * */
  4. public float memoryUsage() {
  5. Map<String, Object> map = new HashMap<String, Object>();
  6. InputStreamReader inputs = null;
  7. BufferedReader buffer = null;
  8. try {
  9. inputs = new InputStreamReader( new FileInputStream( "/proc/meminfo"));
  10. buffer = new BufferedReader(inputs);
  11. String line = "";
  12. while ( true) {
  13. line = buffer.readLine();
  14. if (line == null)
  15. break;
  16. int beginIndex = 0;
  17. int endIndex = line.indexOf( ":");
  18. if (endIndex != - 1) {
  19. String key = line.substring(beginIndex, endIndex);
  20. beginIndex = endIndex + 1;
  21. endIndex = line.length();
  22. String memory = line.substring(beginIndex, endIndex);
  23. String value = memory.replace( "kB", "").trim();
  24. map.put(key, value);
  25. }
  26. }
  27. long memTotal = Long.parseLong(map.get( "MemTotal").toString());
  28. long memFree = Long.parseLong(map.get( "MemFree").toString());
  29. long memused = memTotal - memFree;
  30. long buffers = Long.parseLong(map.get( "Buffers").toString());
  31. long cached = Long.parseLong(map.get( "Cached").toString());
  32. float usage = ( float) (memused - buffers - cached) / memTotal;
  33. return usage;
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. } finally {
  37. try {
  38. buffer.close();
  39. inputs.close();
  40. } catch (Exception e2) {
  41. e2.printStackTrace();
  42. }
  43. }
  44. return 0;
  45. }

  1. /**
  2. * 获取分区的使用占用率
  3. * @param path
  4. * @return
  5. */
  6. public float getPatitionUsage(String path){
  7. File f = new File(path);
  8. long total = f.getTotalSpace();
  9. long free = f.getFreeSpace();
  10. long used = total - free;
  11. float usage = ( float)used/total;
  12. return usage;
  13. }

  1. /**
  2. * 获取磁盘IO使用率
  3. * @return
  4. */
  5. public float getHdIOpPercent() {
  6. System.out.println( "开始收集磁盘IO使用率");
  7. float ioUsage = 0.0f;
  8. Process pro = null;
  9. Runtime r = Runtime.getRuntime();
  10. try {
  11. String command = "iostat -d -x";
  12. pro = r.exec(command);
  13. BufferedReader in = new BufferedReader( new InputStreamReader(pro.getInputStream()));
  14. String line = null;
  15. int count = 0;
  16. while((line=in.readLine()) != null){
  17. if(++count >= 4){
  18. // System.out.println(line);
  19. String[] temp = line.split( "\\s+");
  20. if(temp.length > 1){
  21. float util = Float.parseFloat(temp[temp.length- 1]);
  22. ioUsage = (ioUsage>util)?ioUsage:util;
  23. }
  24. }
  25. }
  26. if(ioUsage > 0){
  27. System.out.println( "本节点磁盘IO使用率为: " + ioUsage);
  28. ioUsage /= 100;
  29. }
  30. in.close();
  31. pro.destroy();
  32. } catch (IOException e) {
  33. StringWriter sw = new StringWriter();
  34. e.printStackTrace( new PrintWriter(sw));
  35. System.out.println( "IoUsage发生InstantiationException. " + e.getMessage());
  36. System.out.println(sw.toString());
  37. }
  38. return ioUsage;
  39. }

  1. /**
  2. * 获取带宽使使用率
  3. * @return
  4. */
  5. public float get() {
  6. float TotalBandwidth = 1000;
  7. System.out.println( "开始收集网络带宽使用率");
  8. float netUsage = 0.0f;
  9. Process pro1,pro2;
  10. Runtime r = Runtime.getRuntime();
  11. try {
  12. String command = "cat /proc/net/dev";
  13. //第一次采集流量数据
  14. long startTime = System.currentTimeMillis();
  15. pro1 = r.exec(command);
  16. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  17. String line = null;
  18. long inSize1 = 0, outSize1 = 0;
  19. while((line=in1.readLine()) != null){
  20. line = line.trim();
  21. if(line.startsWith( "eth0")){
  22. System.out.println(line);
  23. String[] temp = line.split( "\\s+");
  24. inSize1 = Long.parseLong(temp[ 1].substring( 5)); //Receive bytes,单位为Byte
  25. outSize1 = Long.parseLong(temp[ 9]); //Transmit bytes,单位为Byte
  26. break;
  27. }
  28. }
  29. in1.close();
  30. pro1.destroy();
  31. try {
  32. Thread.sleep( 1000);
  33. } catch (InterruptedException e) {
  34. StringWriter sw = new StringWriter();
  35. e.printStackTrace( new PrintWriter(sw));
  36. System.out.println( "NetUsage休眠时发生InterruptedException. " + e.getMessage());
  37. System.out.println(sw.toString());
  38. }
  39. //第二次采集流量数据
  40. long endTime = System.currentTimeMillis();
  41. pro2 = r.exec(command);
  42. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  43. long inSize2 = 0 ,outSize2 = 0;
  44. while((line=in2.readLine()) != null){
  45. line = line.trim();
  46. if(line.startsWith( "eth0")){
  47. System.out.println(line);
  48. String[] temp = line.split( "\\s+");
  49. inSize2 = Long.parseLong(temp[ 1].substring( 5));
  50. outSize2 = Long.parseLong(temp[ 9]);
  51. break;
  52. }
  53. }
  54. if(inSize1 != 0 && outSize1 != 0 && inSize2 != 0 && outSize2 != 0){
  55. float interval = ( float)(endTime - startTime)/ 1000;
  56. //网口传输速度,单位为bps
  57. float curRate = ( float)(inSize2 - inSize1 + outSize2 - outSize1)* 8/( 1000000*interval);
  58. netUsage = curRate/TotalBandwidth;
  59. System.out.println( "本节点网口速度为: " + curRate + "Mbps");
  60. System.out.println( "本节点网络带宽使用率为: " + netUsage);
  61. }
  62. in2.close();
  63. pro2.destroy();
  64. } catch (IOException e) {
  65. StringWriter sw = new StringWriter();
  66. e.printStackTrace( new PrintWriter(sw));
  67. System.out.println( "NetUsage发生InstantiationException. " + e.getMessage());
  68. System.out.println(sw.toString());
  69. }
  70. return netUsage;
  71. }

  1. /**
  2. * 功能:可用磁盘
  3. * */
  4. public static int disk() {
  5. try {
  6. long total = FileSystemUtils.freeSpaceKb( "/");
  7. double disk = ( double) total / 1024 / 1024;
  8. return ( int) disk;
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }
  12. return 0;
  13. }
  14. /**
  15. * 功能:获取Linux系统cpu使用率
  16. * */
  17. public static String cpuUsage() {
  18. try {
  19. Map<?, ?> map1 = SysStatusInfo.cpuinfo();
  20. Thread.sleep( 1 * 1000);
  21. Map<?, ?> map2 = SysStatusInfo.cpuinfo();
  22. long user1 = Long.parseLong(map1.get( "user").toString());
  23. long nice1 = Long.parseLong(map1.get( "nice").toString());
  24. long system1 = Long.parseLong(map1.get( "system").toString());
  25. long idle1 = Long.parseLong(map1.get( "idle").toString());
  26. long user2 = Long.parseLong(map2.get( "user").toString());
  27. long nice2 = Long.parseLong(map2.get( "nice").toString());
  28. long system2 = Long.parseLong(map2.get( "system").toString());
  29. long idle2 = Long.parseLong(map2.get( "idle").toString());
  30. long total1 = user1 + system1 + nice1;
  31. long total2 = user2 + system2 + nice2;
  32. float total = total2 - total1;
  33. long totalIdle1 = user1 + nice1 + system1 + idle1;
  34. long totalIdle2 = user2 + nice2 + system2 + idle2;
  35. float totalidle = totalIdle2 - totalIdle1;
  36. DecimalFormat df = new DecimalFormat( ".0");
  37. float cpusage = ( float)(total / totalidle) * 100;
  38. String value = df.format(cpusage);
  39. return value;
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. return "0";
  44. }
  45. /**
  46. * 功能:CPU使用信息
  47. * */
  48. public static Map<?, ?> cpuinfo() {
  49. InputStreamReader inputs = null;
  50. BufferedReader buffer = null;
  51. Map<String, Object> map = new HashMap<String, Object>();
  52. try {
  53. inputs = new InputStreamReader( new FileInputStream( "/proc/stat"));
  54. buffer = new BufferedReader(inputs);
  55. String line = "";
  56. while ( true) {
  57. line = buffer.readLine();
  58. if (line == null) {
  59. break;
  60. }
  61. if (line.startsWith( "cpu")) {
  62. StringTokenizer tokenizer = new StringTokenizer(line);
  63. List<String> temp = new ArrayList<String>();
  64. while (tokenizer.hasMoreElements()) {
  65. String value = tokenizer.nextToken();
  66. temp.add(value);
  67. }
  68. map.put( "user", temp.get( 1));
  69. map.put( "nice", temp.get( 2));
  70. map.put( "system", temp.get( 3));
  71. map.put( "idle", temp.get( 4));
  72. map.put( "iowait", temp.get( 5));
  73. map.put( "irq", temp.get( 6));
  74. map.put( "softirq", temp.get( 7));
  75. map.put( "stealstolen", temp.get( 8));
  76. break;
  77. }
  78. }
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. } finally {
  82. try {
  83. buffer.close();
  84. inputs.close();
  85. } catch (Exception e2) {
  86. e2.printStackTrace();
  87. }
  88. }
  89. return map;
  90. }

  1. int kb = 1024;
  2. OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
  3. .getOperatingSystemMXBean();
  4. // 操作系统
  5. String osName = System.getProperty( "os.name");
  6. // 总的物理内存
  7. long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
  8. // 剩余的物理内存
  9. long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
  10. // 已使用的物理内存
  11. long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb .getFreePhysicalMemorySize()) / kb;

  1. </pre><pre name= "code" class= "java"> /**
  2. * 获取CPU使用率
  3. * @return
  4. */
  5. public float getCpuUsage() {
  6. System.out.println( "开始收集cpu使用率");
  7. float cpuUsage = 0;
  8. Process pro1,pro2;
  9. Runtime r = Runtime.getRuntime();
  10. try {
  11. String command = "cat /proc/stat";
  12. //第一次采集CPU时间
  13. long startTime = System.currentTimeMillis();
  14. pro1 = r.exec(command);
  15. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  16. String line = null;
  17. long idleCpuTime1 = 0, totalCpuTime1 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
  18. while((line=in1.readLine()) != null){
  19. if(line.startsWith( "cpu")){
  20. line = line.trim();
  21. System.out.println(line);
  22. String[] temp = line.split( "\\s+");
  23. idleCpuTime1 = Long.parseLong(temp[ 4]);
  24. for(String s : temp){
  25. if(!s.equals( "cpu")){
  26. totalCpuTime1 += Long.parseLong(s);
  27. }
  28. }
  29. System.out.println( "IdleCpuTime: " + idleCpuTime1 + ", " + "TotalCpuTime" + totalCpuTime1);
  30. break;
  31. }
  32. }
  33. in1.close();
  34. pro1.destroy();
  35. try {
  36. Thread.sleep( 100);
  37. } catch (InterruptedException e) {
  38. StringWriter sw = new StringWriter();
  39. e.printStackTrace( new PrintWriter(sw));
  40. System.out.println( "CpuUsage休眠时发生InterruptedException. " + e.getMessage());
  41. System.out.println(sw.toString());
  42. }
  43. //第二次采集CPU时间
  44. long endTime = System.currentTimeMillis();
  45. pro2 = r.exec(command);
  46. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  47. long idleCpuTime2 = 0, totalCpuTime2 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
  48. while((line=in2.readLine()) != null){
  49. if(line.startsWith( "cpu")){
  50. line = line.trim();
  51. System.out.println(line);
  52. String[] temp = line.split( "\\s+");
  53. idleCpuTime2 = Long.parseLong(temp[ 4]);
  54. for(String s : temp){
  55. if(!s.equals( "cpu")){
  56. totalCpuTime2 += Long.parseLong(s);
  57. }
  58. }
  59. System.out.println( "IdleCpuTime: " + idleCpuTime2 + ", " + "TotalCpuTime" + totalCpuTime2);
  60. break;
  61. }
  62. }
  63. if(idleCpuTime1 != 0 && totalCpuTime1 != 0 && idleCpuTime2 != 0 && totalCpuTime2 != 0){
  64. cpuUsage = 1 - ( float)(idleCpuTime2 - idleCpuTime1)/( float)(totalCpuTime2 - totalCpuTime1);
  65. System.out.println( "本节点CPU使用率为: " + cpuUsage);
  66. }
  67. in2.close();
  68. pro2.destroy();
  69. } catch (IOException e) {
  70. StringWriter sw = new StringWriter();
  71. e.printStackTrace( new PrintWriter(sw));
  72. System.out.println( "CpuUsage发生InstantiationException. " + e.getMessage());
  73. System.out.println(sw.toString());
  74. }
  75. return cpuUsage;
  76. }

获取MAC:

windows

  1. /**
  2. * 获取MAC地址
  3. *
  4. * @return
  5. */
  6. public String getMac() {
  7. NetworkInterface byInetAddress;
  8. try {
  9. InetAddress localHost = InetAddress.getLocalHost();
  10. byInetAddress = NetworkInterface.getByInetAddress(localHost);
  11. byte[] hardwareAddress = byInetAddress.getHardwareAddress();
  12. return getMacFromBytes(hardwareAddress);
  13. } catch (SocketException e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  17. } catch (UnknownHostException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  21. } catch (Exception e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  25. }
  26. return null;
  27. }
  28. public String getMacFromBytes(byte[] bytes) {
  29. StringBuffer mac = new StringBuffer();
  30. byte currentByte;
  31. boolean first = false;
  32. for ( byte b : bytes) {
  33. if (first) {
  34. mac.append( "-");
  35. }
  36. currentByte = ( byte) ((b & 240) >> 4);
  37. mac.append(Integer.toHexString(currentByte));
  38. currentByte = ( byte) (b & 15);
  39. mac.append(Integer.toHexString(currentByte));
  40. first = true;
  41. }
  42. return mac.toString().toLowerCase();
  43. }

LInux

  1. /**
  2. * 获取MAC
  3. *
  4. * @return
  5. */
  6. public String getMac() {
  7. String result = "";
  8. try {
  9. Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
  10. .getNetworkInterfaces();
  11. while (networkInterfaces.hasMoreElements()) {
  12. NetworkInterface network = networkInterfaces.nextElement();
  13. System.out.println( "network : " + network);
  14. byte[] mac = network.getHardwareAddress();
  15. if (mac == null) {
  16. System.out.println( "null mac");
  17. } else {
  18. System.out.print( "MAC address : ");
  19. StringBuilder sb = new StringBuilder();
  20. for ( int i = 0; i < mac.length; i++) {
  21. sb.append(String.format( "%02X%s", mac[i],
  22. (i < mac.length - 1) ? ":" : ""));
  23. }
  24. result = sb.toString();
  25. System.out.println(sb.toString());
  26. break;
  27. }
  28. }
  29. } catch (SocketException e) {
  30. e.printStackTrace();
  31. }
  32. return result;
  33. }
  1. <pre name= "code" class= "java"> /**
  2. * 获取带宽上传下载速度
  3. * @return
  4. */
  5. public String getNetWorkSpeed() {
  6. boolean result = false;
  7. String detailInfo = "";
  8. DecimalFormat df = new DecimalFormat( "0.00");
  9. String dl = "";
  10. String ul = "";
  11. System.out.println( "开始收集网络带宽使用率");
  12. Process pro1,pro2;
  13. Runtime r = Runtime.getRuntime();
  14. try {
  15. String command = "cat /proc/net/dev";
  16. //第一次采集流量数据
  17. long startTime = System.currentTimeMillis();
  18. pro1 = r.exec(command);
  19. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  20. String line = null;
  21. long inSize1 = 0, outSize1 = 0;
  22. while((line=in1.readLine()) != null){
  23. line = line.trim();
  24. if(line.startsWith( "eth0")){
  25. System.out.println(line);
  26. String[] temp = line.split( "\\s+");
  27. inSize1 = Long.parseLong(temp[ 1]); //Receive bytes,单位为Byte
  28. outSize1 = Long.parseLong(temp[ 9]); //Transmit bytes,单位为Byte
  29. break;
  30. }
  31. }
  32. in1.close();
  33. pro1.destroy();
  34. try {
  35. Thread.sleep( 1000);
  36. } catch (InterruptedException e) {
  37. StringWriter sw = new StringWriter();
  38. e.printStackTrace( new PrintWriter(sw));
  39. System.out.println( "NetUsage休眠时发生InterruptedException. " + e.getMessage());
  40. System.out.println(sw.toString());
  41. }
  42. //第二次采集流量数据
  43. long endTime = System.currentTimeMillis();
  44. pro2 = r.exec(command);
  45. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  46. long inSize2 = 0 ,outSize2 = 0;
  47. while((line=in2.readLine()) != null){
  48. line = line.trim();
  49. if(line.startsWith( "eth0")){
  50. System.out.println(line);
  51. String[] temp = line.split( "\\s+");
  52. inSize2 = Long.parseLong(temp[ 1]);
  53. outSize2 = Long.parseLong(temp[ 9]);
  54. break;
  55. }
  56. }
  57. //cal dl speed
  58. float interval = ( float)(endTime - startTime)/ 1000;
  59. float currentDlSpeed = ( float) (( float)(inSize2 - inSize1)/ 1024/interval);
  60. float currentUlSpeed = ( float) (( float)(outSize2 - outSize1)/ 1024/interval);
  61. if(( float)(currentDlSpeed/ 1024) >= 1){
  62. currentDlSpeed = ( float)(currentDlSpeed/ 1024);
  63. dl = df.format(currentDlSpeed) + "Mb/s";
  64. } else{
  65. dl = df.format(currentDlSpeed) + "Kb/s";
  66. }
  67. if(( float)(currentUlSpeed/ 1024) >= 1){
  68. currentUlSpeed = ( float)(currentUlSpeed/ 1024);
  69. ul = df.format(currentUlSpeed) + "Mb/s";
  70. } else{
  71. ul = df.format(currentUlSpeed) + "Kb/s";
  72. }
  73. result = true;
  74. in2.close();
  75. pro2.destroy();
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. detailInfo = e.getMessage();
  79. }
  80. return "{\"result\":\""+result+ "\",\"detailInfo\":\""+detailInfo+ "\",\"dl\":\""+dl+ "\",\"ul\":\""+ul+ "\"}";
  81. }


 
  
  1. /**
  2. * 功能:内存使用率
  3. * */
  4. public float memoryUsage() {
  5. Map<String, Object> map = new HashMap<String, Object>();
  6. InputStreamReader inputs = null;
  7. BufferedReader buffer = null;
  8. try {
  9. inputs = new InputStreamReader( new FileInputStream( "/proc/meminfo"));
  10. buffer = new BufferedReader(inputs);
  11. String line = "";
  12. while ( true) {
  13. line = buffer.readLine();
  14. if (line == null)
  15. break;
  16. int beginIndex = 0;
  17. int endIndex = line.indexOf( ":");
  18. if (endIndex != - 1) {
  19. String key = line.substring(beginIndex, endIndex);
  20. beginIndex = endIndex + 1;
  21. endIndex = line.length();
  22. String memory = line.substring(beginIndex, endIndex);
  23. String value = memory.replace( "kB", "").trim();
  24. map.put(key, value);
  25. }
  26. }
  27. long memTotal = Long.parseLong(map.get( "MemTotal").toString());
  28. long memFree = Long.parseLong(map.get( "MemFree").toString());
  29. long memused = memTotal - memFree;
  30. long buffers = Long.parseLong(map.get( "Buffers").toString());
  31. long cached = Long.parseLong(map.get( "Cached").toString());
  32. float usage = ( float) (memused - buffers - cached) / memTotal;
  33. return usage;
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. } finally {
  37. try {
  38. buffer.close();
  39. inputs.close();
  40. } catch (Exception e2) {
  41. e2.printStackTrace();
  42. }
  43. }
  44. return 0;
  45. }

  1. /**
  2. * 获取分区的使用占用率
  3. * @param path
  4. * @return
  5. */
  6. public float getPatitionUsage(String path){
  7. File f = new File(path);
  8. long total = f.getTotalSpace();
  9. long free = f.getFreeSpace();
  10. long used = total - free;
  11. float usage = ( float)used/total;
  12. return usage;
  13. }

  1. /**
  2. * 获取磁盘IO使用率
  3. * @return
  4. */
  5. public float getHdIOpPercent() {
  6. System.out.println( "开始收集磁盘IO使用率");
  7. float ioUsage = 0.0f;
  8. Process pro = null;
  9. Runtime r = Runtime.getRuntime();
  10. try {
  11. String command = "iostat -d -x";
  12. pro = r.exec(command);
  13. BufferedReader in = new BufferedReader( new InputStreamReader(pro.getInputStream()));
  14. String line = null;
  15. int count = 0;
  16. while((line=in.readLine()) != null){
  17. if(++count >= 4){
  18. // System.out.println(line);
  19. String[] temp = line.split( "\\s+");
  20. if(temp.length > 1){
  21. float util = Float.parseFloat(temp[temp.length- 1]);
  22. ioUsage = (ioUsage>util)?ioUsage:util;
  23. }
  24. }
  25. }
  26. if(ioUsage > 0){
  27. System.out.println( "本节点磁盘IO使用率为: " + ioUsage);
  28. ioUsage /= 100;
  29. }
  30. in.close();
  31. pro.destroy();
  32. } catch (IOException e) {
  33. StringWriter sw = new StringWriter();
  34. e.printStackTrace( new PrintWriter(sw));
  35. System.out.println( "IoUsage发生InstantiationException. " + e.getMessage());
  36. System.out.println(sw.toString());
  37. }
  38. return ioUsage;
  39. }

  1. /**
  2. * 获取带宽使使用率
  3. * @return
  4. */
  5. public float get() {
  6. float TotalBandwidth = 1000;
  7. System.out.println( "开始收集网络带宽使用率");
  8. float netUsage = 0.0f;
  9. Process pro1,pro2;
  10. Runtime r = Runtime.getRuntime();
  11. try {
  12. String command = "cat /proc/net/dev";
  13. //第一次采集流量数据
  14. long startTime = System.currentTimeMillis();
  15. pro1 = r.exec(command);
  16. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  17. String line = null;
  18. long inSize1 = 0, outSize1 = 0;
  19. while((line=in1.readLine()) != null){
  20. line = line.trim();
  21. if(line.startsWith( "eth0")){
  22. System.out.println(line);
  23. String[] temp = line.split( "\\s+");
  24. inSize1 = Long.parseLong(temp[ 1].substring( 5)); //Receive bytes,单位为Byte
  25. outSize1 = Long.parseLong(temp[ 9]); //Transmit bytes,单位为Byte
  26. break;
  27. }
  28. }
  29. in1.close();
  30. pro1.destroy();
  31. try {
  32. Thread.sleep( 1000);
  33. } catch (InterruptedException e) {
  34. StringWriter sw = new StringWriter();
  35. e.printStackTrace( new PrintWriter(sw));
  36. System.out.println( "NetUsage休眠时发生InterruptedException. " + e.getMessage());
  37. System.out.println(sw.toString());
  38. }
  39. //第二次采集流量数据
  40. long endTime = System.currentTimeMillis();
  41. pro2 = r.exec(command);
  42. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  43. long inSize2 = 0 ,outSize2 = 0;
  44. while((line=in2.readLine()) != null){
  45. line = line.trim();
  46. if(line.startsWith( "eth0")){
  47. System.out.println(line);
  48. String[] temp = line.split( "\\s+");
  49. inSize2 = Long.parseLong(temp[ 1].substring( 5));
  50. outSize2 = Long.parseLong(temp[ 9]);
  51. break;
  52. }
  53. }
  54. if(inSize1 != 0 && outSize1 != 0 && inSize2 != 0 && outSize2 != 0){
  55. float interval = ( float)(endTime - startTime)/ 1000;
  56. //网口传输速度,单位为bps
  57. float curRate = ( float)(inSize2 - inSize1 + outSize2 - outSize1)* 8/( 1000000*interval);
  58. netUsage = curRate/TotalBandwidth;
  59. System.out.println( "本节点网口速度为: " + curRate + "Mbps");
  60. System.out.println( "本节点网络带宽使用率为: " + netUsage);
  61. }
  62. in2.close();
  63. pro2.destroy();
  64. } catch (IOException e) {
  65. StringWriter sw = new StringWriter();
  66. e.printStackTrace( new PrintWriter(sw));
  67. System.out.println( "NetUsage发生InstantiationException. " + e.getMessage());
  68. System.out.println(sw.toString());
  69. }
  70. return netUsage;
  71. }

  1. /**
  2. * 功能:可用磁盘
  3. * */
  4. public static int disk() {
  5. try {
  6. long total = FileSystemUtils.freeSpaceKb( "/");
  7. double disk = ( double) total / 1024 / 1024;
  8. return ( int) disk;
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }
  12. return 0;
  13. }
  14. /**
  15. * 功能:获取Linux系统cpu使用率
  16. * */
  17. public static String cpuUsage() {
  18. try {
  19. Map<?, ?> map1 = SysStatusInfo.cpuinfo();
  20. Thread.sleep( 1 * 1000);
  21. Map<?, ?> map2 = SysStatusInfo.cpuinfo();
  22. long user1 = Long.parseLong(map1.get( "user").toString());
  23. long nice1 = Long.parseLong(map1.get( "nice").toString());
  24. long system1 = Long.parseLong(map1.get( "system").toString());
  25. long idle1 = Long.parseLong(map1.get( "idle").toString());
  26. long user2 = Long.parseLong(map2.get( "user").toString());
  27. long nice2 = Long.parseLong(map2.get( "nice").toString());
  28. long system2 = Long.parseLong(map2.get( "system").toString());
  29. long idle2 = Long.parseLong(map2.get( "idle").toString());
  30. long total1 = user1 + system1 + nice1;
  31. long total2 = user2 + system2 + nice2;
  32. float total = total2 - total1;
  33. long totalIdle1 = user1 + nice1 + system1 + idle1;
  34. long totalIdle2 = user2 + nice2 + system2 + idle2;
  35. float totalidle = totalIdle2 - totalIdle1;
  36. DecimalFormat df = new DecimalFormat( ".0");
  37. float cpusage = ( float)(total / totalidle) * 100;
  38. String value = df.format(cpusage);
  39. return value;
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. return "0";
  44. }
  45. /**
  46. * 功能:CPU使用信息
  47. * */
  48. public static Map<?, ?> cpuinfo() {
  49. InputStreamReader inputs = null;
  50. BufferedReader buffer = null;
  51. Map<String, Object> map = new HashMap<String, Object>();
  52. try {
  53. inputs = new InputStreamReader( new FileInputStream( "/proc/stat"));
  54. buffer = new BufferedReader(inputs);
  55. String line = "";
  56. while ( true) {
  57. line = buffer.readLine();
  58. if (line == null) {
  59. break;
  60. }
  61. if (line.startsWith( "cpu")) {
  62. StringTokenizer tokenizer = new StringTokenizer(line);
  63. List<String> temp = new ArrayList<String>();
  64. while (tokenizer.hasMoreElements()) {
  65. String value = tokenizer.nextToken();
  66. temp.add(value);
  67. }
  68. map.put( "user", temp.get( 1));
  69. map.put( "nice", temp.get( 2));
  70. map.put( "system", temp.get( 3));
  71. map.put( "idle", temp.get( 4));
  72. map.put( "iowait", temp.get( 5));
  73. map.put( "irq", temp.get( 6));
  74. map.put( "softirq", temp.get( 7));
  75. map.put( "stealstolen", temp.get( 8));
  76. break;
  77. }
  78. }
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. } finally {
  82. try {
  83. buffer.close();
  84. inputs.close();
  85. } catch (Exception e2) {
  86. e2.printStackTrace();
  87. }
  88. }
  89. return map;
  90. }

  1. int kb = 1024;
  2. OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
  3. .getOperatingSystemMXBean();
  4. // 操作系统
  5. String osName = System.getProperty( "os.name");
  6. // 总的物理内存
  7. long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
  8. // 剩余的物理内存
  9. long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
  10. // 已使用的物理内存
  11. long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb .getFreePhysicalMemorySize()) / kb;

  1. </pre><pre name= "code" class= "java"> /**
  2. * 获取CPU使用率
  3. * @return
  4. */
  5. public float getCpuUsage() {
  6. System.out.println( "开始收集cpu使用率");
  7. float cpuUsage = 0;
  8. Process pro1,pro2;
  9. Runtime r = Runtime.getRuntime();
  10. try {
  11. String command = "cat /proc/stat";
  12. //第一次采集CPU时间
  13. long startTime = System.currentTimeMillis();
  14. pro1 = r.exec(command);
  15. BufferedReader in1 = new BufferedReader( new InputStreamReader(pro1.getInputStream()));
  16. String line = null;
  17. long idleCpuTime1 = 0, totalCpuTime1 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
  18. while((line=in1.readLine()) != null){
  19. if(line.startsWith( "cpu")){
  20. line = line.trim();
  21. System.out.println(line);
  22. String[] temp = line.split( "\\s+");
  23. idleCpuTime1 = Long.parseLong(temp[ 4]);
  24. for(String s : temp){
  25. if(!s.equals( "cpu")){
  26. totalCpuTime1 += Long.parseLong(s);
  27. }
  28. }
  29. System.out.println( "IdleCpuTime: " + idleCpuTime1 + ", " + "TotalCpuTime" + totalCpuTime1);
  30. break;
  31. }
  32. }
  33. in1.close();
  34. pro1.destroy();
  35. try {
  36. Thread.sleep( 100);
  37. } catch (InterruptedException e) {
  38. StringWriter sw = new StringWriter();
  39. e.printStackTrace( new PrintWriter(sw));
  40. System.out.println( "CpuUsage休眠时发生InterruptedException. " + e.getMessage());
  41. System.out.println(sw.toString());
  42. }
  43. //第二次采集CPU时间
  44. long endTime = System.currentTimeMillis();
  45. pro2 = r.exec(command);
  46. BufferedReader in2 = new BufferedReader( new InputStreamReader(pro2.getInputStream()));
  47. long idleCpuTime2 = 0, totalCpuTime2 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
  48. while((line=in2.readLine()) != null){
  49. if(line.startsWith( "cpu")){
  50. line = line.trim();
  51. System.out.println(line);
  52. String[] temp = line.split( "\\s+");
  53. idleCpuTime2 = Long.parseLong(temp[ 4]);
  54. for(String s : temp){
  55. if(!s.equals( "cpu")){
  56. totalCpuTime2 += Long.parseLong(s);
  57. }
  58. }
  59. System.out.println( "IdleCpuTime: " + idleCpuTime2 + ", " + "TotalCpuTime" + totalCpuTime2);
  60. break;
  61. }
  62. }
  63. if(idleCpuTime1 != 0 && totalCpuTime1 != 0 && idleCpuTime2 != 0 && totalCpuTime2 != 0){
  64. cpuUsage = 1 - ( float)(idleCpuTime2 - idleCpuTime1)/( float)(totalCpuTime2 - totalCpuTime1);
  65. System.out.println( "本节点CPU使用率为: " + cpuUsage);
  66. }
  67. in2.close();
  68. pro2.destroy();
  69. } catch (IOException e) {
  70. StringWriter sw = new StringWriter();
  71. e.printStackTrace( new PrintWriter(sw));
  72. System.out.println( "CpuUsage发生InstantiationException. " + e.getMessage());
  73. System.out.println(sw.toString());
  74. }
  75. return cpuUsage;
  76. }

获取MAC:

windows

  1. /**
  2. * 获取MAC地址
  3. *
  4. * @return
  5. */
  6. public String getMac() {
  7. NetworkInterface byInetAddress;
  8. try {
  9. InetAddress localHost = InetAddress.getLocalHost();
  10. byInetAddress = NetworkInterface.getByInetAddress(localHost);
  11. byte[] hardwareAddress = byInetAddress.getHardwareAddress();
  12. return getMacFromBytes(hardwareAddress);
  13. } catch (SocketException e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  17. } catch (UnknownHostException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  21. } catch (Exception e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. System.out.println(getLocalTime()+ "获取mac地址失败:" + e.getMessage());
  25. }
  26. return null;
  27. }
  28. public String getMacFromBytes(byte[] bytes) {
  29. StringBuffer mac = new StringBuffer();
  30. byte currentByte;
  31. boolean first = false;
  32. for ( byte b : bytes) {
  33. if (first) {
  34. mac.append( "-");
  35. }
  36. currentByte = ( byte) ((b & 240) >> 4);
  37. mac.append(Integer.toHexString(currentByte));
  38. currentByte = ( byte) (b & 15);
  39. mac.append(Integer.toHexString(currentByte));
  40. first = true;
  41. }
  42. return mac.toString().toLowerCase();
  43. }

LInux

  1. /**
  2. * 获取MAC
  3. *
  4. * @return
  5. */
  6. public String getMac() {
  7. String result = "";
  8. try {
  9. Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
  10. .getNetworkInterfaces();
  11. while (networkInterfaces.hasMoreElements()) {
  12. NetworkInterface network = networkInterfaces.nextElement();
  13. System.out.println( "network : " + network);
  14. byte[] mac = network.getHardwareAddress();
  15. if (mac == null) {
  16. System.out.println( "null mac");
  17. } else {
  18. System.out.print( "MAC address : ");
  19. StringBuilder sb = new StringBuilder();
  20. for ( int i = 0; i < mac.length; i++) {
  21. sb.append(String.format( "%02X%s", mac[i],
  22. (i < mac.length - 1) ? ":" : ""));
  23. }
  24. result = sb.toString();
  25. System.out.println(sb.toString());
  26. break;
  27. }
  28. }
  29. } catch (SocketException e) {
  30. e.printStackTrace();
  31. }
  32. return result;
  33. }

猜你喜欢

转载自blog.csdn.net/taoy86/article/details/80925080