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,
- Able to connect to remote machine RM1.
- Able to execute single/multiple commands on RM1 (followed this https://www.journaldev.com/246/jsch-example-java-ssh-unix-server and https://stackoverflow.com/a/5831846/8773024 ).
- Able to connect to remote machine RM1 and again connect to another remote machine RM2.
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");