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

一、前言

通过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@}@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 memoryUsage () throws Exception {@b@BufferedReader freeReader = null;@b@@b@String      freeLine;@b@String[]    freeChunkedLine;@b@@b@HashMap usageData = new HashMap();@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@}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值