Sample code for 30+ languages & platforms
C

Connect to an SSH Server Through Another (Jump Host)

See more SSH Examples

Demonstrates the Chilkat Ssh.ConnectThroughSsh method, which connects to a second SSH server through an already connected and authenticated Ssh object. The first argument is the first (jump-host) Ssh object, and the second and third are the destination hostname and port.

Background: This is SSH chaining through a "jump host" (bastion): the application connects to a reachable gateway, then tunnels onward to a target that is only accessible from inside the network. Each hop is authenticated separately with its own credentials. The result is a normal Ssh object for the target that happens to be routed through the first connection.

Chilkat C Downloads

C
#include <C_CkSsh.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkSsh sshJump;
    int sshPort;
    const char *password;
    HCkSsh sshTarget;

    success = FALSE;

    //  Demonstrates the Ssh.ConnectThroughSsh method, which connects to a second SSH server through
    //  an already connected and authenticated Ssh object (a jump host).  The 1st argument is the
    //  first Ssh object, and the 2nd and 3rd are the destination hostname and port.

    sshJump = CkSsh_Create();

    //  Connect and authenticate to the first SSH server (the jump host).
    sshPort = 22;
    success = CkSsh_Connect(sshJump,"jump.example.com",sshPort);
    if (success == FALSE) {
        printf("%s\n",CkSsh_lastErrorText(sshJump));
        CkSsh_Dispose(sshJump);
        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 = "mySshPassword";

    success = CkSsh_AuthenticatePw(sshJump,"jumpUser",password);
    if (success == FALSE) {
        printf("%s\n",CkSsh_lastErrorText(sshJump));
        CkSsh_Dispose(sshJump);
        return;
    }

    //  Connect to the target SSH server through the jump host.
    sshTarget = CkSsh_Create();
    success = CkSsh_ConnectThroughSsh(sshTarget,sshJump,"target.example.com",sshPort);
    if (success == FALSE) {
        printf("%s\n",CkSsh_lastErrorText(sshTarget));
        CkSsh_Dispose(sshJump);
        CkSsh_Dispose(sshTarget);
        return;
    }

    //  Authenticate to the target server (separate credentials).
    success = CkSsh_AuthenticatePw(sshTarget,"targetUser",password);
    if (success == FALSE) {
        printf("%s\n",CkSsh_lastErrorText(sshTarget));
        CkSsh_Dispose(sshJump);
        CkSsh_Dispose(sshTarget);
        return;
    }

    printf("Connected to the target through the jump host.\n");

    CkSsh_Disconnect(sshTarget);
    CkSsh_Disconnect(sshJump);


    CkSsh_Dispose(sshJump);
    CkSsh_Dispose(sshTarget);

    }