使用ganymed-ssh2-build通过ssh获得远程服务器参数
生活随笔
收集整理的這篇文章主要介紹了
使用ganymed-ssh2-build通过ssh获得远程服务器参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、項目中需要檢測到幾臺遠程服務器的參數,差了很多資料,決定用的這個
2、jar包:ganymed-ssh2-build210.jar
3、原理:向遠程linux服務器發送腳本命令,得到該臺服務器的信息
4、代碼如下:
public class Basic {
public static void main(String[] args) {
String hostname1 = "";
String username1 = "";
String password1 = "";
String hostname2 = "";
String username2 = "";
String password2 = "";
String hostname3 = "";
String username3 = "";
String password3 = "";
/**
* 服務器1
*/
Montor montor1 = getMontor(hostname1, username1, password1);
/**
* 服務器2
*/
Montor montor2 = getMontor(hostname2, username2, password2);
/**
* 服務器3
*/
Montor montor3 = getMontor(hostname3, username3, password3);
System.out.println(montor1.toString());
System.out.println(montor2.toString());
System.out.println(montor3.toString());
}
private static Montor getMontor(String hostname, String username,
String password) {
Montor montor = null;
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated;
isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
montor = new Montor();
montor.setHostName(exec(conn, "hostname"));
montor.setDiskSpace(exec(conn, "df -h | awk 'NR==2 {print $2}'"));
montor.setUserSpace(exec(conn, "df -h | awk 'NR==2 {print $3}'"));
montor.setRemainingSpace(exec(conn,
"df -h | awk 'NR==2 {print $4}'"));
montor.setMemory(exec(conn, "free -m | awk 'NR==2 {print $2}'"));
montor.setUseMemory(exec(conn, "free -m | awk 'NR==2 {print $3}'"));
montor.setRemainingMemory(exec(conn,
"free -m | awk 'NR==2 {print $4}'"));
BigDecimal b1 = new BigDecimal(exec(conn,
"free -m | awk 'NR==2 {print $3}'"));
BigDecimal b2 = new BigDecimal(exec(conn,
"free -m | awk 'NR==2 {print $2}'"));
montor.setUsageMemory((b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP))
.doubleValue()
* 100 + "%");
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return montor;
};
/**
*
* @param conn 連接
* @param command 執行的sheel命令
* @return
*/
private static String exec(Connection conn, String command) {
String data = "";
try {
Session sess = conn.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;
data = line;
}
br.close();
sess.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
return data;
}
}
5、目前還需要服務器中各項服務的聯通性,如tomcat,active-mq等服務 是否掛機,如有大嬸知道,望告知
6、如果還有其他更好的方式望周知。
總結
以上是生活随笔為你收集整理的使用ganymed-ssh2-build通过ssh获得远程服务器参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2017 网站打包发布生成的文件中包
- 下一篇: transform、transition