I'm using JSCH lib
to execute some mongodb
commands on remote machine, I have a program which has three methods those are
connect(serverIP, userName, password)
: it will connect to server and there is linesession.connect()
throwing below exceptions
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)
: it will execute the command and print resultdisconnect()
: it will disconnect from server.
I've attached the code below of three methods.
Question : If we use session.connect()
without knowing server is available in network or not,its throwing Exception JschException:NotRouteToHostException
.
Is there any way to validate server is available in network or not, Instead of getting exception?
If yes how can we do validate?
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();
}