JSch Shell channel execute commands one by one testing result before proceeding

后端 未结 1 446
春和景丽
春和景丽 2020-12-10 23:26

I have a program for connecting to a SSH shell. I was able to execute the commands and read output from it.

But I have a new requirement. Now I need to execute a com

相关标签:
1条回答
  • 2020-12-11 00:01

    In general you should use an "exec" channel for this. The "shell" channel should not be used to automate a command execution.

    But I understand that your server does not support the "exec" channel. I've added the above comment for the other readers, not to try to use this solution, unless they really have to.


    As @Yair Harel already commented, if you have to use the "shell" channel, you have to use shell techniques.

    So in your particular case, you may want to have the remote shell print some unique string and the exit code after the command finishes:

    out.println(command + " ; echo Command-has-finished-with-code-$?");
    

    Then you keep reading the output until you find a line starting "Command-has-finished-with-code-". You parse the exit code and decide how to proceed.

    Note that the command syntax (particularly the command separator character ; and exit code variable $?) is OS- and shell-specific. As your server is not of a standard kind, the syntax may be different.


    Side notes:

    • The "#!/bin/bash" is a pure nonsense. The shell ignores all commands starting with # (it's comment). There's no point sending it.
    • Do not use StrictHostKeyChecking=no. See JSch SFTP security with session.setConfig("StrictHostKeyChecking", "no");
    0 讨论(0)
提交回复
热议问题