Sample code for 30+ languages & platforms
C++

Run a Command on an SSH Session Channel

See more SSH Examples

Demonstrates the Chilkat Ssh.SendReqExec method, which requests execution of a command on a session channel. The first argument is the channel number and the second is the command line. This example runs a command, reads the output until the channel closes, and prints it.

Background: exec is the workhorse for automation: run one command, collect its output, and finish — no interactive shell needed. Note carefully that a true return means the request was accepted, not that the command succeeded. To learn the command's outcome, read its output and check the channel exit status.

Chilkat C++ Downloads

C++
#include <CkSsh.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Demonstrates the Ssh.SendReqExec method, which requests execution of a command on a session
    //  channel.  The 1st argument is the channel number and the 2nd is the command line.

    CkSsh ssh;

    int sshPort = 22;
    success = ssh.Connect("ssh.example.com",sshPort);
    if (success == false) {
        std::cout << ssh.lastErrorText() << "\r\n";
        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.
    const char *password = "mySshPassword";

    success = ssh.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        std::cout << ssh.lastErrorText() << "\r\n";
        return;
    }

    //  Open a session channel.  A negative return value indicates failure.
    int channelNum = ssh.OpenSessionChannel();
    if (channelNum < 0) {
        std::cout << ssh.lastErrorText() << "\r\n";
        return;
    }

    //  Request execution of a command.  A true return means the server accepted the request; it
    //  does not mean the command itself succeeded.
    success = ssh.SendReqExec(channelNum,"ls -l /tmp");
    if (success == false) {
        std::cout << ssh.lastErrorText() << "\r\n";
        return;
    }

    //  IMPORTANT: Set a read timeout.  ReadTimeoutMs defaults to 0, which means no limit -- without
    //  it, this call waits forever if the server never sends channel close.
    ssh.put_ReadTimeoutMs(15000);

    //  Read the command output until the server closes the channel.
    success = ssh.ChannelReceiveToClose(channelNum);
    if (success == false) {
        std::cout << ssh.lastErrorText() << "\r\n";
        return;
    }

    const char *output = ssh.getReceivedText(channelNum,"utf-8");
    if (ssh.get_LastMethodSuccess() == false) {
        std::cout << ssh.lastErrorText() << "\r\n";
        return;
    }

    std::cout << output << "\r\n";

    ssh.Disconnect();
    }