问题
I understand how to create a ssh shell
Shell ssh = new SshByPassword("192.168.1.5", 22, "admin", "password");
i also understand how to run a command
String output = new Shell.Plain(ssh).exec("some command");
and i can easly analyze the output string
but how do i send in the same "shell" one command after the other
and bonus question sometimes the commands require a user confirmation ("press Y to continue")
is it possible with the library?
回答1:
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();
来源:https://stackoverflow.com/questions/60289826/using-java-jcabi-ssh-client-or-other-to-execute-several-commands-in-shell