应用Ganymed SSH-2 for Java判断服务器状态:
之前的很多章节已经描述了如何运用Ganymed SSH-2 for Java的api,基本上主要的都进行过演示了。
下面,我将通过一个实际中很有帮助的一个功能点作为应用的开篇,讲述这个在实际工作中的意义。
一台服务器,如何判断其状态是否正常啦,及是否可以访问,在不想登录等操作的情况下,每隔一段时间探测一次服务状态,那么可以这样实现:
/**
* 探测服务器状态
*
* @param host
* @param username
* @param password
* @param cmd
* @param port
* @return
* @throws IOException
*/
public static String queryServerStatus(String host, String username,
String password,
String cmd, int port) throws IOException {
if (logger.isInfoEnabled()) {
logger.info("running SSH cmd [" + cmd + "]");
}
Connection conn = null;
Session sess = null;
InputStream stdOut = null;
String outStr = "";
try {
conn = getOpenedConnection(host, username, password, port);
sess = conn.openSession();
sess.execCommand(cmd);
stdOut = new StreamGobbler(sess.getStdout());
outStr = FileWRUtil.inputStream2String(stdOut,
ConstantsUtil.CHARSET);
sess.waitForCondition(ChannelCondition.EXIT_STATUS, 60000);
} finally {
if (null != sess) {
sess.close();
sess = null;
}
if (null != conn) {
conn.close();
conn = null;
}
IOUtils.closeQuietly(stdOut);
}
return outStr;
}
测试代码:
String cmd = "curl -o /dev/null -s -m 10 --connect-timeout 60 -w %{http_code} 'http://172.16.18.141:8080/Login.jsp'";
System.out.println(CommandRunner.queryServerStatus("172.16.18.141",
"weblogic", "123456", cmd, 22));