java中遠端監控Linux主機CPU及記憶體程式碼實現
阿新 • • 發佈:2019-01-22
對於遠端監控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組資料
* 顯示結果如下:
* [ [email protected] ~]$ 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組資料
* 顯示結果如下:
* [ [email protected] ~]$ 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;
}
}
執行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組資料
* 顯示結果如下:
* [
* 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組資料
* 顯示結果如下:
* [
* 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;
}
}