首页

关于基于ganymed-ssh2源码包定义LinuxUtils工具类实现执行linux操作系统ssh命令、获取内存及CPU监控数据等代码示例

标签:ganymed-ssh2,LinuxUtils,linux工具类,linux,ssh命令,内存memoryUsage,cpuUsage     发布时间:2018-08-02   

一、前言

通过ganymed-ssh2源码包ch.ethz.ssh2.Connection、ch.ethz.ssh2.Session定义linux命令行ssh操作LinuxUtils工具类,实现ssh命令的exec执行、执行远程ip执行remoteExec、获取系统cpu实时监控cpuUsage性能参数、获取系统内存memoryUsage性能参数等。

二、示例代码

import java.io.BufferedReader;@b@import java.io.InputStream;@b@import java.io.InputStreamReader;@b@import java.io.IOException;@b@import java.lang.Process;@b@import java.lang.Runtime;@b@import java.util.HashMap;@b@@b@import ch.ethz.ssh2.Connection;@b@import ch.ethz.ssh2.Session;@b@import ch.ethz.ssh2.StreamGobbler;@b@@b@public class LinuxUtils@b@{@b@	public static final int CONSERVATIVE    = 0;@b@	public static final int AVERAGE     = 1;@b@	public static final int OPTIMISTIC  = 2;@b@@b@	public static String exec(String command) {@b@		BufferedReader reader = null;@b@		try {@b@			Process process = Runtime.getRuntime().exec(command);@b@			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));@b@			StringBuffer ret = new StringBuffer();@b@			String line;@b@			while ((line = reader.readLine()) != null) {@b@				ret.append(line + "\r\n");@b@			}@b@			reader.close();@b@			return ret.toString();@b@		} catch (Exception e) {@b@			e.printStackTrace();@b@		} finally {@b@			if (reader != null) try { reader.close(); } catch (Exception e) { }@b@		}@b@		return "";@b@	}@b@@b@	public static String remoteExec(String ip, String name, String password, String command) {@b@		Connection connection = null;@b@		Session session = null;@b@		BufferedReader reader = null;@b@		try {@b@			connection = new Connection(ip);  @b@			connection.connect();@b@			boolean isAuthenticated = connection.authenticateWithPassword(name, password);  @b@			if (isAuthenticated) {@b@				session = connection.openSession();  @b@				session.execCommand(command);  @b@				InputStream stdout = new StreamGobbler(session.getStdout());  @b@				reader = new BufferedReader(new InputStreamReader(stdout));@b@				StringBuffer ret = new StringBuffer();@b@				String line;@b@				while ((line = reader.readLine()) != null) {@b@					ret.append(line + "\r\n");@b@				}@b@				return ret.toString();@b@			} else {@b@				System.out.printf("ssh[%s@%s]: auth failed!", name, ip);@b@			}@b@		} catch (Exception e) {@b@			e.printStackTrace();@b@		} finally {@b@			if (reader != null) try { reader.close(); } catch (Exception e) { }@b@			if (session != null) try { session.close(); } catch (Exception e) { }@b@			if (connection != null) try { connection.close(); } catch (Exception e) { }@b@		}@b@		return "";@b@	}@b@@b@	/**@b@	 * cpuUsage gives us the percentage of cpu usage@b@	 * @b@	 * mpstat -P ALL out stream example:@b@	 *@b@	 *  Linux 3.2.0-30-generic (castarco-laptop)    10/09/12    _x86_64_    (2 CPU)                 - To discard@b@	 *                                                                                              - To discard@b@	 *  00:16:30     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle    - To discard@b@	 *  00:16:30     all   17,62    0,03    3,55    0,84    0,00    0,03    0,00    0,00   77,93@b@	 *  00:16:30       0   17,36    0,05    3,61    0,83    0,00    0,05    0,00    0,00   78,12@b@	 *  00:16:30       1   17,88    0,02    3,49    0,86    0,00    0,01    0,00    0,00   77,74@b@	 * @b@	 * @param measureMode Indicates if we want optimistic, convervative or average measurements.@b@	 */@b@	public static Double cpuUsage (int measureMode) throws Exception {@b@@b@		BufferedReader mpstatReader = null;@b@@b@		String      mpstatLine;@b@		String[]    mpstatChunkedLine;@b@		Double      selected_idle;@b@@b@		try {@b@			Runtime runtime = Runtime.getRuntime();@b@			Process mpstatProcess = runtime.exec("mpstat -P ALL");@b@@b@			mpstatReader = new BufferedReader(new InputStreamReader(mpstatProcess.getInputStream()));@b@@b@			// We discard the three first lines@b@			mpstatReader.readLine();@b@			mpstatReader.readLine();@b@			mpstatReader.readLine();@b@@b@			mpstatLine = mpstatReader.readLine();@b@			if (mpstatLine == null) {@b@				throw new Exception("mpstat didn't work well");@b@			} else if (measureMode == LinuxUtils.AVERAGE) {@b@				mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");@b@				selected_idle = Double.parseDouble(mpstatChunkedLine[10]);@b@			} else {@b@				selected_idle   = (measureMode == LinuxUtils.CONSERVATIVE)?200.:0.;@b@				Double candidate_idle;@b@@b@				int i = 0;@b@				while((mpstatLine = mpstatReader.readLine()) != null) {@b@					mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");@b@					candidate_idle = Double.parseDouble(mpstatChunkedLine[10]);@b@@b@					if (measureMode == LinuxUtils.CONSERVATIVE) {@b@						selected_idle = (selected_idle < candidate_idle)?selected_idle:candidate_idle;@b@					} else if (measureMode == LinuxUtils.OPTIMISTIC) {@b@						selected_idle = (selected_idle > candidate_idle)?selected_idle:candidate_idle;@b@					}@b@					++i;@b@				}@b@				if (i == 0) {@b@					throw new Exception("mpstat didn't work well");@b@				}@b@			}@b@		} catch (Exception e) {@b@			throw e; // It's not desirable to handle the exception here@b@		} finally {@b@			if (mpstatReader != null) try { mpstatReader.close(); } catch (IOException e) { }@b@		}@b@@b@		return  100-selected_idle;@b@	}@b@@b@	/**@b@	 * memoryUsage gives us data about memory usage (RAM and SWAP)@b@	 */@b@	public static HashMap<String, Integer> memoryUsage () throws Exception {@b@		BufferedReader freeReader = null;@b@@b@		String      freeLine;@b@		String[]    freeChunkedLine;@b@@b@		HashMap<String, Integer> usageData = new HashMap<String, Integer>();@b@@b@		try {@b@			Runtime runtime = Runtime.getRuntime();@b@			Process freeProcess = runtime.exec("free -k"); // We measure memory in kilobytes to obtain a greater granularity@b@@b@			freeReader = new BufferedReader(new InputStreamReader(freeProcess.getInputStream()));@b@@b@			// We discard the first line@b@			freeReader.readLine();@b@@b@			freeLine = freeReader.readLine();@b@			if (freeLine == null) {@b@				throw new Exception("free didn't work well");@b@			}@b@			freeChunkedLine = freeLine.split("\\s+");@b@@b@			usageData.put("total", Integer.parseInt(freeChunkedLine[1]));@b@@b@			freeLine = freeReader.readLine();@b@			if (freeLine == null) {@b@				throw new Exception("free didn't work well");@b@			}@b@			freeChunkedLine = freeLine.split("\\s+");@b@@b@			usageData.put("used", Integer.parseInt(freeChunkedLine[2]));@b@@b@			freeLine = freeReader.readLine();@b@			if (freeLine == null) {@b@				throw new Exception("free didn't work well");@b@			}@b@			freeChunkedLine = freeLine.split("\\s+");@b@@b@			usageData.put("swap_total", Integer.parseInt(freeChunkedLine[1]));@b@			usageData.put("swap_used", Integer.parseInt(freeChunkedLine[2]));@b@		} catch (Exception e) {@b@			throw e;@b@		} finally {@b@			if (freeReader != null) try { freeReader.close(); } catch (IOException e) { }@b@		}@b@		return usageData;@b@	}@b@}
<<推荐下载>>
  • (1) 阿里巴巴Java开发手册8种不同版本
  • (2) Web前端开发视频教程
  • (3) 30+明星讲师PPT课件分享一线大厂架构实战经验
  • (4) java开发_架构篇_视频资源分享_v2208
  • (5) java开发_高级篇_视频资源分享_v2208
  • (6) java开发_进阶篇(中级)_视频资源分享_v2208
  • (7) java开发_入门篇_视频资源分享_v2208
  • (8) 微信小程序开发视频1+167源码+实战demo等下载
  • (9) easy-shopping电子商务java源码(附脚本和安装文档说明)下载
  • (10) java常用的72份知名实用的电子书下载
  • (11) java开发性能优化资料整理大全(8份电子文档+3份实战优化)下载
  • (12) 9个常用的算法设计资料和100以上视频课件内容下载
  • (13) vue开发必备常用手册16件下载
  • (14) 21种不同技术集群方案(es、flink、redis、nginx、zk、lvs、kafka、mysql、k8s等)参考资料下载
  • (15) 20种技术代码规范(js/java/dba/阿里/华为/oracle/mysql等)参考资料下载
  • (16) 微服务五套资料(0-1,架构设计,springcloud,nacos等)下载
  • (17) 架构师(28知识图谱+3套简历模板+6套架构实战文档等)完整资料整理下载
  • (18) 大数据18套实战基础知识+8套简历模板下载
  • (19) 并发编程全套(7套+阿里巴巴+亿级实战等)实战资料下载
  • (20) Kafka九套学习整理知识点全套(面试+笔记+代码api+命令+容备等)资料下载
  • (21) java全套9个不同方向类型的面试题(基础+核心+大厂+架构师+近万套题库等)下载
  • (22) JAVA开发常用API帮助文档大全(超52种以上技术资料,高手必备)下载
  • (23) springcloud超详细139件全套学习实战资料( 视频课件+源码demo+文档资料等)下载
  • 更多推荐>>
  • <<热门文章>>