How to run and display the result of a shell command ssh with JSch?

后端 未结 2 1323
逝去的感伤
逝去的感伤 2021-02-10 15:16

I try to use the library JSch - Java Secure Channel make an ssh connection in my Android app, it works.

Now I would like to execute a command and retrie

相关标签:
2条回答
  • 2021-02-10 15:43

    Your method stops in the loop (instead of finishing it) because the remote shell doesn't close the output stream. It has no reason to do this, since there you could send more commands.

    If you only want to execute a single command (or a series of commands known before), you shouldn't use a Shell channel, but an "exec" channel.

    This way the remote shell (which executes your command) will finish when your command is finished, and then the server will close the stream. So your loop will finish, and then you can close the streams.

    If you think you need a shell channel (for example, if you need to fire up multiple commands in the same context, and react to one's output before deciding what would be the next one), you'll need some way to know when one command is finished (e.g. by recognizing the prompt), and then send the next one. To quit, either close the output stream or send a "logout" or "exit" command (both work with any standard unix shell, other shells might need different commands), then the remote site should close the other stream, too.

    By the way, while disabling strict host key checking is convenient, it also opens up your connection to a man-in-the-middle attack, and in case of password authentication, the attacker can grab your password. The right way to do this would be to set up a correctly initialized host key repository to recognize the remote host's key.

    0 讨论(0)
  • 2021-02-10 15:54

    As far as I am aware JSch is the only real option.

    I have found that Jsch errors tend to take some digging. But in the first instance you will want to catch and print out the errors as a minimum.

    try{ 
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, port);
        ... omitted 
     } catch (Exception e) {
         System.out.println(e) 
     }
    

    also have a look a the example code on the site

    0 讨论(0)
提交回复
热议问题