Multiple commands through JSch shell

前端 未结 4 1498
不知归路
不知归路 2020-11-30 01:05

I was trying to execute multiple commands through SSH protocol using the JSch library. But I seem to have stuck and cannot find any solution. The setCommand() m

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 01:28

    Avoid using "shell" channel as much as possible. The "shell" channel is intended to implement an interactive session, not to automate a command execution. With "shell" channel, you will face many unwanted side effects.

    To automate a command execution, use "exec" channel.


    Usually, you can open as many "exec" channels as you need, using each to execute one of your commands. You can open the channels in sequence or even in parallel.

    For a complete example of "exec" channel use, see JSch Exec.java example.

    This way each command executes in an isolated environment. What may be an advantage, but it can also be undesirable in some cases.


    If you need to execute commands in a way that previous commands affect later commands (like changing a working directory or setting an environment variable), you have to execute all commands in the same channel. Use an appropriate construct of the server's shell for that. On most systems you can use semicolons:

    execChannel.setCommand("command1 ; command2 ; command3");
    

    On *nix servers, you can also use && to make the following commands be executed only when the previous commands succeeded:

    execChannel.setCommand("command1 && command2 && command3");
    

    See also Execute a list of commands from an ArrayList using JSch exec in Java.


    Most complicated situation is, when the commands depend on one another and you need to process results of previous commands before proceeding to other commands.

    When you have such need, it usually indicates a bad design. Think hard, if this is really the only solution to your problem. Or consider implementing a server-side shell script to implement the logic, instead of doing it remotely from Java code. Shell scripts have much more powerful techniques to check for results of previous commands, then you have with SSH interface in JSch.

    Anyway, see JSch Shell channel execute commands one by one testing result before proceeding.


    Side note: Do not use StrictHostKeyChecking=no. See JSch SFTP security with session.setConfig("StrictHostKeyChecking", "no");.

提交回复
热议问题