Rohan Karn Rohan Karn - 1 year ago 112
Java Question

JSch: Run command after Multi-Level ssh

I am using JSch to run some commands after multi-level ssh:

public static void main(String[] args) {

String user="User0";
String ip="IP0";
int port=22;
String password="Password0";
JSch jsch= new JSch();
Session session=null;
ChannelExec channel=null;
try {
session=(jsch.getSession(user, ip, port));
session.setConfig("StrictHostKeyChecking", "no");
String dir=Reomte_DIR;
String cmd1=SomeComplexCommand;
String cmd2=SomeMoreComplexCommand;
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("ssh User1@IP1_PasswordLessLogin;ssh User2@IP2_PasswordLessLogin; "+cmd1+" ; "+cmd2+" ;");
String res = null;
BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(channel.getErrStream()));
if ((res = error.readLine()) == null) {
res = input.readLine()+input.readLine()+input.readLine()+input.readLine();
} else {

res = "-1";

} catch (JSchException e) {
}catch (IOException e) {
}finally {

but it doesn't give desired result.

hangs. If I remove multilevel ssh, everything works fine!
Am i doing something wrong??

I got some hint from: Multi-level SSH login in Java and Multiple commands using Jsch but i am not able to get my code running.

Answer Source

Your command is wrong.

Your command will execute the first command ssh User1@IP1_PasswordLessLogin.

And then it will wait for it to finish before executing the second command.

  • The first ssh command never finishes, as it will forever keep waiting for user to type commands.
  • Even if the first ssh ever finished, the second ssh would be executed on the initial host, not one the IP1.

You need something like this:

ssh User1@IP1_PasswordLessLogin ssh User2@IP2_PasswordLessLogin "<cmd1> ; <cmd2>"

This tells the first ssh to execute the second ssh on the IP1; and the second ssh to execute the <cmd1> ; <cmd2> on the IP2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download