Sample code for 30+ languages & platforms
Unicode C

SSH Execute Remote Commands

See more SSH Examples

Demonstrates running several commands on an SSH server using QuickCommand, which performs the entire open-channel, exec, receive, and retrieve sequence in a single call and returns the command's stdout.

Background: QuickCommand is the simplest way to run one-off commands: each call uses its own session channel on the same authenticated connection, so several commands can be issued in sequence without managing channels yourself. Because no PTY is involved the output is clean, with no prompt or echoed input to strip. Reach for the individual channel methods only when you need stderr separately, the exit status, or a long-lived interactive session.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkSshW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkSshW ssh;
    int port;
    const wchar_t *password;
    const wchar_t *strOutput;

    success = FALSE;

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    //  Demonstrates running several commands on an SSH server using QuickCommand, which handles the
    //  whole open-channel, exec, receive, and retrieve sequence in a single call.

    ssh = CkSshW_Create();

    port = 22;
    success = CkSshW_Connect(ssh,L"ssh.example.com",port);
    if (success == FALSE) {
        wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
        CkSshW_Dispose(ssh);
        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.
    password = L"mySshPassword";

    success = CkSshW_AuthenticatePw(ssh,L"mySshLogin",password);
    if (success == FALSE) {
        wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
        CkSshW_Dispose(ssh);
        return;
    }

    //  Each QuickCommand call runs one command on its own session channel and returns its stdout.
    strOutput = CkSshW_quickCommand(ssh,L"df",L"utf-8");
    if (CkSshW_getLastMethodSuccess(ssh) == FALSE) {
        wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
        CkSshW_Dispose(ssh);
        return;
    }

    wprintf(L"---- df ----\n");
    wprintf(L"%s\n",strOutput);

    strOutput = CkSshW_quickCommand(ssh,L"echo hello world",L"utf-8");
    if (CkSshW_getLastMethodSuccess(ssh) == FALSE) {
        wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
        CkSshW_Dispose(ssh);
        return;
    }

    wprintf(L"---- echo hello world ----\n");
    wprintf(L"%s\n",strOutput);

    strOutput = CkSshW_quickCommand(ssh,L"date",L"utf-8");
    if (CkSshW_getLastMethodSuccess(ssh) == FALSE) {
        wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
        CkSshW_Dispose(ssh);
        return;
    }

    wprintf(L"---- date ----\n");
    wprintf(L"%s\n",strOutput);

    CkSshW_Disconnect(ssh);


    CkSshW_Dispose(ssh);

    }