我正在使用 JSCH lib
在远程机器上执行一些 mongodb
命令,我有一个程序有三种方法
connect(serverIP, userName, password)
:它将连接到服务器并且有线路
session.connect()
抛出异常
If invalid credentails: JschException:Auth Fail
,
If SSH is not enabled in server :JschException:java.net.ConnectException: Connection refused
If server is not in network: JschException:java.net.NoRouteToHostException: No route to host
-
executeCommand(command)
:它将执行命令和打印结果 -
disconnect()
:它将与服务器断开连接 .
我已经附上了三种方法的代码 .
问题:如果我们使用 session.connect()
而不知道网络中是否有可用的服务器,则抛出异常 JschException:NotRouteToHostException
.
有没有办法验证服务器是否可用于网络,而不是获得异常?
如果是,我们如何进行验证?
public void connect(String serverIP, String serverUserName, String password ){
JSch jsch = new JSch();
try {
session = jsch.getSession(serverUserName, serverIP, 22);
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
try {
session.connect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public StringBuffer executeCommand(String script) throws JSchException, IOException{
String sudo_pass = "test";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
((ChannelExec) channel).setCommand( script);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
StringBuffer commandResult = new StringBuffer();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
commandResult.append(new String(tmp, 0, i));
Logger.of(LoggerConstants.AUTOMATTER_LOGGER).debug(new String(tmp, 0, i));
Logger.of(LoggerConstants.AUTOMATTER_LOGGER).info(new String(tmp, 0, i));
//System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
//System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
System.out.println("Sudo disconnect");
return commandResult;
}
public void disconnect(){
session.disconnect();
}