使用 SSH-2 for Java 来确定服务器状态:
前面的很多章节已经描述了如何使用 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));