ganymed ssh2的监控应用

        背景:系统上线了,正式环境服务器的一些硬件数据需要监控。写一个小工程,调取服务器的硬件使用信息。有页面展示,有定时数据采集。结局方式定为在LINUX服务器端设置脚本采集数据。通过JAVA端SSH连接获取采集结果。

       JAVA端要和LINUX交互,采用的方式是ganymed ssh2。导入ganymed-ssh2-build210.jar之后,看了看例子,连接方式还算比较清晰。

首先先做一个封装,形成一个基础的Client端。

1.通过login方法获得连接实例

2.通过execShellCommand方法执行LINUX命令,并返回结果为字符串

3.closeConnection释放连接。

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
 
 
public final class SSHGanymedUtil { 
 
     
     
    private String hostname; 
 
     
    private int port; 
 
     
    private String username; 
 
     
    private String password; 
 
     
    private long taskId; 
 
     
    private Connection connection; 
 
     
    public SSHGanymedUtil(String _hostname, int _port, String _username, 
            String _password) { 
        this.hostname = _hostname; 
        this.port = _port; 
        this.username = _username; 
        this.password = _password; 
    } 
 
     
    public SSHGanymedUtil(String _hostname, int _port, String _username, 
            String _password, Long id) { 
        this(_hostname, _port, _username, _password); 
        this.taskId = id; 
    } 
 
     
    public void login() throws Exception { 
        System.out.println("start task id is " + taskId);
        // 建立连接 
        connection = new Connection(hostname, port); 
        try { 
            // 连接上 
            connection.connect(); 
 
            // 进行校验 
            boolean isAuthenticated = connection.authenticateWithPassword( 
                    username, password); 
            System.out.println("isAuthenticated = " + isAuthenticated);
            if (isAuthenticated == false) 
                throw new IOException("Authentication failed."); 
 
        } catch (Exception e) { 
            e.printStackTrace();
            throw new Exception("UserOrPasswordError"); 
        } 
    } 
    public String execShellCommand(final String command){
    	Session sess = null; 
    	StringBuilder sb = new StringBuilder();
    	try{
    		sess = connection.openSession();
    		sess.execCommand(command);
    		InputStream stdout = new StreamGobbler(sess.getStdout());
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
			while (true)
			{
				String line = br.readLine();
				if (line == null)
					break;
				sb.append(line);
			}
    	}
    	catch (Throwable e) { 
        	e.printStackTrace();
        } finally { 
            // 关闭通道 
            if (sess != null) 
                sess.close(); 
        } 
    	return sb.toString(); 
    }
     
   
 
     
    public void closeConnection() { 
    	System.out.println("end task id is " + taskId + "disconnet");
        if (connection != null) 
            connection.close(); 
    } 
 
    public String getHostname() { 
        return hostname; 
    } 
 
    public void setHostname(String hostname) { 
        this.hostname = hostname; 
    } 
 
    public int getPort() { 
        return port; 
    } 
 
    public void setPort(int port) { 
        this.port = port; 
    } 
 
    public String getUsername() { 
        return username; 
    } 
 
    public void setUsername(String username) { 
        this.username = username; 
    } 
 
    public String getPassword() { 
        return password; 
    } 
 
    public void setPassword(String password) { 
        this.password = password; 
    } 
 
     
}   

 应用方式

 

 

    SSHGanymedUtil ssh = new SSHGanymedUtil(IP,PORT,ROOT,PWD);
	try {
	    ssh.login();
	} catch (Exception e) {
	    e.printStackTrace();//连接异常要捕获
	}
	    String result = ssh.execShellCommand(COMMAND);//执行命令,返回结果
	    ssh.closeConnection();//得到结果及时释放连接

 另外附上linux端脚本

#!/bin/bash
echo "mysql;"
mysql_status=`netstat -tnul | grep -v "grep" | grep "3306" | wc -l`
if [ $mysql_status -eq 1 ]
then
echo "mysql:up;"
else
echo "mysql:down;"
fi
echo "ip:`ifconfig | grep 'inet addr:'|awk 'NR==1{print $2}'|awk -F: '{print $2}'`;"
echo "disk:`df -h |awk 'NR==2 {print $5}'`;"
echo "mem:`free -m | sed -n '2p' | awk '{print $3/$2*100"%"}'`;"
echo "cpu:`/usr/bin/vmstat | tail -1 | awk '{print 100-$15}'`;"
Cpu_num=`grep -c "model name" /proc/cpuinfo`
Cpu_15_load=`uptime  | awk -F "," '{print $NF}' | cut -f 1 -d "."`
echo "cpu I/O:$Cpu_15_load;"

 

 

你可能感兴趣的:(java,ssh)