Sample code for 30+ languages & platforms
Java

SSH Remote Shell with Multiple Commands

See more SSH Examples

Demonstrates running several commands one after another in a single remote shell session, retrieving each command's output separately. No PTY is requested, so each command is followed by an echoed marker that signals where its output ends.

Background: Interleaving commands and reads in one shell requires a way to know where each command's output stops. An interactive session would use the shell prompt, but without a PTY the shell is non-interactive and never prints one — so the dependable technique is to append echo SOME_MARKER to each command and read up to that marker. Retrieving the text also clears the receive buffer, which matters here: if a marker were left buffered, the next receive would match it immediately and return the wrong output.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ssh;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // Demonstrates running several commands one after another in a single remote shell session,
        // retrieving each command's output separately.
        //
        // No PTY is requested, so the shell runs non-interactively and never prints a command prompt.
        // Because there is no prompt to synchronize on, each command is followed by an "echo" of a
        // unique marker, and the output is read up to that marker.

        Ssh ssh = new Ssh();

        String hostname = "ssh.example.com";
        int port = 22;
        try {
            ssh.connect(hostname, port);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Normally you would not hard-code the password in source.  You should instead obtain it
        // from an interactive prompt, environment variable, or a secrets vault.
        String password = "mySshPassword";

        try {
            ssh.authenticatePw("mySshLogin", password);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int channelNum = ssh.openSessionChannel();
        if (channelNum < 0) {
            System.out.println(ssh.getLastErrorText());
            return;
        }

        // Start a shell WITHOUT requesting a PTY.  Without a PTY the shell sees it is connected to a
        // raw data pipe and enters non-interactive mode: it suppresses the command prompt, does not
        // echo typed commands back, and skips interactive login scripts.  The output is therefore
        // clean and easily parseable -- but because no prompt is ever sent, code must not wait for
        // one.  Instead, have each command print a predictable marker, or wait for EOF / channel close.
        try {
            ssh.sendReqShell(channelNum);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // IMPORTANT: Set a read timeout before receiving until a match.  ReadTimeoutMs defaults to 0,
        // which means no limit -- without it, this call waits forever if the received data never
        // contains a match.
        ssh.setReadTimeoutMs(15000);

        boolean caseSensitive = true;

        // ---- 1st command: change directory ----
        String cmdOutput;
        try {
            ssh.channelSendString(channelNum, "cd /tmp; echo END_OF_CMD_1\n", "utf-8");

            ssh.channelReceiveUntilMatch(channelNum, "END_OF_CMD_1", "utf-8", caseSensitive);

            // Retrieving the text also clears the receive buffer, which matters: if the next marker were
            // left in the buffer, the following receive would match immediately.
            cmdOutput = ssh.getReceivedText(channelNum, "utf-8");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(cmdOutput);

        // ---- 2nd command: directory listing ----
        try {
            ssh.channelSendString(channelNum, "ls; echo END_OF_CMD_2\n", "utf-8");

            ssh.channelReceiveUntilMatch(channelNum, "END_OF_CMD_2", "utf-8", caseSensitive);

            cmdOutput = ssh.getReceivedText(channelNum, "utf-8");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(cmdOutput);

        // ---- 3rd command: long listing, then finish the session ----
        try {
            ssh.channelSendString(channelNum, "ls -l\n", "utf-8");

            // No more input will be sent.
            ssh.channelSendEof(channelNum);

            ssh.channelReceiveToClose(channelNum);

            cmdOutput = ssh.getReceivedText(channelNum, "utf-8");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(cmdOutput);

        ssh.disconnect();
    }
}