java中远程监控Linux主机CPU及内存代码实现

对于远程监控Linux主机系统CPU,内存使用情况,以前也使用了top等命令,但是最后还是觉得使用vmstat比较好.


运行top命令获得系统CPU使用情况有两个缺点,


第一运行top命令,执行的shell语句相对复杂.
用top命令获得CPU使用情况的shell语句
top -b -n 2 | grep Cpu |sed 1d | awk '{print $5}' | cut -f 1 -d "."
第二:有时候系统峰值时间很短暂,容易造成误判.




注意:运行本例子,你还需要下载第三方ganymed-ssh2-build251beta1.jar,改软件主要用于通过ssh远程登录被监控主机.


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.*;
public class test{

public static void main(String[] args) {
Connection conn = null;
boolean isAuthenticated = false;
try
{
/* Create a connection instance */


conn = new Connection(hostname); // hostname 你要远程登录的主机IP地址,如10.0.2.1


/* Now connect */

conn.connect();

/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/


isAuthenticated = conn.authenticateWithPassword(username, password); //你要远程登录的主机的用户名及密码,如admin/123456
//System.out.println("authenticate sucess ...........................");
if (isAuthenticated == false)
System.out.println("SSH Login  Authentication failed.");
else
{
/* Create a session */
Session sess = conn.openSession();
System.out.println(new SysCpuInfo(sess).getCPUInfo());
/*注意,一个session只能执行一次shell,因此,如果你要再执行shell的话,必须重新创建一个session*/
sess.close();
sess = conn.openSession();
System.out.println(new SysMemInfo(sess).getMEMInfo());
sess.close();
}
}catch(Exception e){System.out.println(e.toString());}


}


1.读取CPU信息(SysCpuInfo.java)


import java.io.*;
import java.lang.*;
import java.util.StringTokenizer;


import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;


public class SysCpuInfo {


private int CPU_IDLE=0;
int processStatus =0;

public SysCpuInfo(Session session)
{
InputStream is = null;
BufferedReader brStat = null;
StringTokenizer tokenStat=  null ;
Session sess = null;
String str = "";
int i=0,j=0,cpuidle=0;

/**
* 对于执行linux shell.
*/
try{
sess = session;
sess.execCommand("vmstat 2 10 ");
/**
* 执行vmstat命令获得系统CPU负载情况,vmstat 2 10表示2秒钟输出一次共输出10组数据
* 显示结果如下:
* [mon724@v0A-202-40-18 ~]$ vmstat 2 10
* procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
* r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
* 1  0  41328  58860 199292 1877728    0    0     2    23    0    0  2  0 98  0  0
* 0  0  41328  58744 199292 1877884    0    0     0     0 1080 1057  3  0 96  0  0
* 0  0  41328  58084 199300 1878036    0    0     0   250 1310 1258  6  0 94  0  0
* 0  0  41328  57844 199300 1878148    0    0     0    32  761  697  3  0 97  0  0
* 0  0  41328  57852 199304 1878224    0    0     0   214  630  593  1  1 98  0  0
* 0  0  41328  56984 199304 1878372    0    0     0    50 1033  881  6  0 94  0  0
* 0  0  41328  56860 199304 1878440    0    0     0     0  536  578  2  0 98  0  0
* 1  0  41328  56868 199308 1878552    0    0     0   200  545  581  1  0 99  0  0
* 0  0  41328  56876 199308 1878644    0    0     0   102  628  663  1  0 99  0  0
* 0  0  41328  56876 199308 1878696    0    0     0   118  615  580  3  0 96  0  0 
*/
is = new StreamGobbler(sess.getStdout());


brStat = new BufferedReader(new InputStreamReader(is));
/*先读取第一行Title信息
* procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
* */
brStat.readLine();
/*读取第二行Title信息读取第三行信息
*  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
* */
brStat.readLine();

/*读取第三行信息
*  1  0  41328  58860 199292 1877728    0    0     2    23    0    0  2  0 98  0  0
*  注意每次执行vmstat命令时,此行信息基本不变,因此不做为抽取数据使用
* */
brStat.readLine();
/*读取第4行到第12行信息
*/
for(j=0;j<9;j++)
{
str = brStat.readLine();
if(str==null)
break;
tokenStat = new StringTokenizer(str);
for(i=0;i<14;i++)
{
tokenStat.nextToken();
}
cpuidle = cpuidle+new Integer(tokenStat.nextToken()).intValue();
}
CPU_IDLE = new Double(cpuidle/9).intValue();

}catch(Exception e){System.out.println(e.toString());}
}

public int getCPUInfo()
{
return CPU_IDLE;
}


}


2.读取内存信息(SysMemInfo.java)
import java.io.*;
import java.lang.*;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.StringTokenizer;


import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;


public class SysMemInfo {




private int MEM_INFO=0;



public SysMemInfo(Session session,String hostname)
{
InputStream is = null;
BufferedReader brStat = null;
StringTokenizer tokenStat=  null ;
Session sess = null;
String str = "";
int i=0,j=0,free=0,buff=0,cache=0,totalmemory=0,memidle=0;
double memused=0;
DataBaseCon datacon = null;
ResultSet reset ;
Statement stmt = null;
/**
* 对于执行linux shell中存在重定向和管道过滤的命令,需要使用命令组的形式.
*/
try{
datacon = new DataBaseCon();
stmt = datacon.getDBconnection().createStatement();

reset = stmt.executeQuery("select TOTAL_MEMORY from machine_info where machine_ip='"+hostname+"'");
while(reset.next())
{
totalmemory = reset.getInt("TOTAL_MEMORY");
}
sess = session;
sess.execCommand("vmstat 2 10 ");
/**
* 执行vmstat命令获得系统CPU负载情况,vmstat 2 10表示2秒钟输出一次共输出10组数据
* 显示结果如下:
* [mon724@v0A-202-40-18 ~]$ vmstat 2 10
* procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
* r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
* 1  0  41328  58860 199292 1877728    0    0     2    23    0    0  2  0 98  0  0
* 0  0  41328  58744 199292 1877884    0    0     0     0 1080 1057  3  0 96  0  0
* 0  0  41328  58084 199300 1878036    0    0     0   250 1310 1258  6  0 94  0  0
* 0  0  41328  57844 199300 1878148    0    0     0    32  761  697  3  0 97  0  0
* 0  0  41328  57852 199304 1878224    0    0     0   214  630  593  1  1 98  0  0
* 0  0  41328  56984 199304 1878372    0    0     0    50 1033  881  6  0 94  0  0
* 0  0  41328  56860 199304 1878440    0    0     0     0  536  578  2  0 98  0  0
* 1  0  41328  56868 199308 1878552    0    0     0   200  545  581  1  0 99  0  0
* 0  0  41328  56876 199308 1878644    0    0     0   102  628  663  1  0 99  0  0
* 0  0  41328  56876 199308 1878696    0    0     0   118  615  580  3  0 96  0  0 
*/
is = new StreamGobbler(sess.getStdout());


brStat = new BufferedReader(new InputStreamReader(is));
/*先读取第一行Title信息
* procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
* */
brStat.readLine();
/*读取第二行Title信息读取第三行信息
*  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
* */
brStat.readLine();

/*读取第三行信息
*  1  0  41328  58860 199292 1877728    0    0     2    23    0    0  2  0 98  0  0
*  注意每次执行vmstat命令时,此行信息基本不变,因此不做为抽取数据使用
* */
brStat.readLine();
/*读取第4行到第12行信息
*/
for(j=0;j<9;j++)
{
str = brStat.readLine();

if(str==null)
break;
tokenStat = new StringTokenizer(str);
/*跳过每行前3列信息
* r  b   swpd   
    * 1  0  41328
* */
for(i=0;i<3;i++)
{
tokenStat.nextToken();
}
/*
* 读取每行中free,buff,cache列信息
* r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
    * 1  0  41328  58860 199292 1877728    0    0     2    23    0    0  2  0 98  0  0

* */
/*读取free的信息*/
free =  free+new Integer(tokenStat.nextToken()).intValue();
//SysLogger.log("free is :"+free);
/*读取buff的信息*/
buff =  buff+new Integer(tokenStat.nextToken()).intValue();
//SysLogger.log("buff is :"+buff);
/*读取cache的信息*/
cache = cache+new Integer(tokenStat.nextToken()).intValue();
//SysLogger.log("cache is :"+cache);

}
/*
* ===========================================================
* 获得内存IDLE的平均值,因为读取了9行数据因此需要除于9得出平均值
* 对于应用程序来说系统真正的内存空余是free+buff+cache之和
* ===========================================================
* */
memidle = (free+buff+cache)/9;
/*获得内存占用率*/
memused = ((totalmemory-memidle)*100)/totalmemory;
//SysLogger.log("SysMemInfo memidle is :"+memidle+"===memused is :"+memused);
MEM_INFO = new Double(memused).intValue();
SysLogger.log("SysMemInfo MEM_INFO IS : "+MEM_INFO);
}catch(Exception e){SysLogger.log("SysMemInfo error at line 39 :"+e.toString());}
}


public int getMEMInfo()
{
return MEM_INFO;
}
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现电脑远程控制的方式有很多种,其常见的方法是使用 Socket 编程实现远程控制。下面是一个简单的 Java 实现远程控制的示例代码: Server 端代码: ```java import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { ServerSocket server = new ServerSocket(8888); System.out.println("等待客户端连接..."); Socket socket = server.accept(); System.out.println("客户端已连接:" + socket.getRemoteSocketAddress()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("收到客户端消息:" + inputLine); if (inputLine.equals("exit")) { break; } else { Runtime.getRuntime().exec(inputLine); out.println("命令已执行"); } } in.close(); out.close(); socket.close(); server.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` Client 端代码: ```java import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); if (userInput.equals("exit")) { break; } else { System.out.println("服务器回复:" + in.readLine()); } } in.close(); out.close(); stdIn.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码实现了一个简单的远程控制功能,可以通过客户端向服务器发送命令实现远程控制。需要注意的是,这个示例代码只是为了演示远程控制的原理,实际使用还需要进行安全性考虑,避免被非法操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值