I need to execute some sequence of commands at the remote server via ssh, using sshj library.
I do
Session session = ssh.startSession();
Session.Command cmd = session.exec("ls -l");
System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join(10, TimeUnit.SECONDS);
Session.Command cmd2 = session.exec("ls -a");
System.out.println(IOUtils.readFully(cmd2.getInputStream()).toString());
and it throws me
net.schmizz.sshj.common.SSHRuntimeException: This session channel is all used up
But I can't recreate session for every single command, because this example it will show home directory list, but not the /some/dir list.
As odd as it is,
session
can only be used once. So you have to reset the session every time.Or if the shell you are connecting to supports delimited commands (and the situation allows it), you can do this (bash example):
session.exec("ls -l; <command 2>; <command 3>");
This question is old but just to clarify, quoting from the wiki https://github.com/hierynomus/sshj/wiki
In our case we have made put it in a function
You can consider using an Expect-like third party library which simplifies working with remote services and capturing output. Those libraries are designed to execute a sequence of commands. Here is a good set of options you can try:
However, when I was about to solve similar problem I found these libraries are rather old. They also introduce a lot of unwanted dependencies. So I created my own and made it available for others. It is called ExpectIt. The advantages of my library it are stated on the project home page. You can give it a try.
Here is an example of interacting with a public remote SSH service using sshj:
Here is the link to the complete workable example.