Sample code for 30+ languages & platforms
PureBasic

Authenticate an SSH Tunnel with a Private Key

See more Socket/SSL/TLS Examples

Demonstrates Socket.SshAuthenticatePk, which authenticates an SSH tunnel session using a private key loaded into an SshKey object. Call SshOpenTunnel first.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The SSH server must have the corresponding public key authorized for the account. If the private key is encrypted, set the SshKey.Password property before loading it.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkSocket.pb"
IncludeFile "CkSshKey.pb"

Procedure ChilkatExample()

    success.i = 0

    socket.i = CkSocket::ckCreate()
    If socket.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkSocket::ckSshOpenTunnel(socket,"ssh.example.com",22)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        ProcedureReturn
    EndIf

    ;  Load the SSH private key.  The file path is relative to the application's current working
    ;  directory.  If the key is encrypted, set the SshKey.Password property before calling
    ;  FromOpenSshPrivateKey.
    sshKey.i = CkSshKey::ckCreate()
    If sshKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    keyText.s = CkSshKey::ckLoadText(sshKey,"qa_data/id_ed25519")
    If CkSshKey::ckLastMethodSuccess(sshKey) = 0
        Debug CkSshKey::ckLastErrorText(sshKey)
        CkSocket::ckDispose(socket)
        CkSshKey::ckDispose(sshKey)
        ProcedureReturn
    EndIf

    success = CkSshKey::ckFromOpenSshPrivateKey(sshKey,keyText)
    If success = 0
        Debug CkSshKey::ckLastErrorText(sshKey)
        CkSocket::ckDispose(socket)
        CkSshKey::ckDispose(sshKey)
        ProcedureReturn
    EndIf

    ;  Authenticate the SSH tunnel session using public-key authentication.  The SSH server must have the
    ;  corresponding public key authorized for the account.
    success = CkSocket::ckSshAuthenticatePk(socket,"sshUser",sshKey)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        CkSshKey::ckDispose(sshKey)
        ProcedureReturn
    EndIf

    Debug "SSH public-key authentication succeeded."


    CkSocket::ckDispose(socket)
    CkSshKey::ckDispose(sshKey)


    ProcedureReturn
EndProcedure