I am trying to execute multiple commands on remote machine though SSH using the JSch library. i am almost there but stuck in one command.
I am using two remote machines lets say RM1 and RM2
Able to do following steps,
Not able to do this step, 1. Once i will be connected to remote machine RM2 after this not able to execute any command.
Please let me know if anyone can help me on this.
I tried this code:
String host="IP";
String user="username";
String password="password";
String command1="pwd";
String command2="ssh -tt user@ip";
String command3="pwd";
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel1=session.openChannel("exec");
((ChannelExec)channel1).setCommand(command1;command2;command3);
channel1.setInputStream(null);
((ChannelExec)channel1).setErrStream(System.err);
InputStream in1=channel1.getInputStream();
channel1.connect();
byte[] tmp=new byte[1024];
while(true){
while(in1.available()>0){
int i=in1.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel1.isConnected()){
System.out.println("exit-status: "+channel1.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
Try executing pwd;ssh -tt user@ip;pwd
in a normal SSH terminal client connected to the RM1. It won't work, So it won't work in Java either.
To do the "jump", you should use port forwarding (see JSch JumpHosts
example), instead of executing ssh
on the jump server.