Using java jcabi SSH client (or other) to execute several commands in shell

橙三吉。 提交于 2020-05-17 07:28:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!