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
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:
"#!/bin/bash"
is a pure nonsense. The shell ignores all commands starting with #
(it's comment). There's no point sending it. StrictHostKeyChecking=no
. See JSch SFTP security with session.setConfig("StrictHostKeyChecking", "no");