Generally, most Java SSH APIs leave it to the developer to sort out the complexities of executing multiple commands within a shell. It is a complicated problem because SSH does not provide any indication of where commands start and end within the shell; the protocol only provides a stream of data, which is the raw output of the shell.
I would humbly like to introduce my project Maverick Synergy. An open-source API (LGPL) that does provide an interface for interactive shells. I documented the options for interactive commands in an article.
Here is a very basic example, the ExpectShell class allows you to execute multiple commands, each time returning a ShellProcess that encapsulates the command output. You can use the ShellProcess InputStream to read the output, it will return EOF when the command is done.
You can also use a ShellProcessController to interact with the command as this example shows.
SshClient ssh = new SshClient("localhost", 22, "lee", "xxxxxx".toCharArray());
ssh.runTask(new ShellTask(ssh) {
protected void onOpenSession(SessionChannelNG session)
throws IOException, SshException, ShellTimeoutException {
ExpectShell shell = new ExpectShell(this);
// Execute the first command
ShellProcess process = shell.executeCommand("ls -l");
process.drain();
String output = process.getCommandOutput();
// After processing output execute another
ShellProcessController controller =
new ShellProcessController(
shell.executeCommand("rm -i file.txt"));
if(controller.expect("remove")) {
controller.typeAndReturn("y");
}
controller.getProcess().drain();
}
});
ssh.disconnect();