Sample code for 30+ languages & platforms
Tcl

Connect an SSH Tunnel to the SSH Server

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.Connect method, which establishes the SSH connection that carries the tunnel's traffic. The first argument is the SSH server hostname and the second is the port. It performs the connection, SSH handshake, and host-key negotiation, but does not authenticate the SSH user.

Background: Connecting establishes only the SSH transport — the encrypted channel and host-key exchange. It is the point at which the server's identity becomes known, so it is where a security-conscious client checks HostKeyFingerprint against a trusted value before handing over credentials. Authentication and BeginAccepting follow; nothing is forwarded until they do.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates the SshTunnel.Connect method, which establishes the SSH connection that carries
#  tunneled traffic.  The 1st argument is the SSH server hostname and the 2nd is the port.  This
#  performs the connection, SSH handshake, and host-key negotiation, but does not authenticate.

set tunnel [new_CkSshTunnel]

#  The tunnel forwards accepted local connections to this destination through the SSH server.
CkSshTunnel_put_DestHostname $tunnel "db.internal.example.com"
CkSshTunnel_put_DestPort $tunnel 5432

#  Connect to the SSH server.  This performs the TCP/proxy connection and SSH handshake, but
#  does not authenticate yet.
set sshPort 22
set success [CkSshTunnel_Connect $tunnel "ssh.example.com" $sshPort]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

#  Optionally verify the server's host key before authenticating.
puts "Host key fingerprint: [CkSshTunnel_hostKeyFingerprint $tunnel]"

#  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.
set password "mySshPassword"

set success [CkSshTunnel_AuthenticatePw $tunnel "mySshLogin" $password]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

#  After authenticating, call BeginAccepting to start listening for local connections to forward.

set waitForThreadExit 1
set success [CkSshTunnel_CloseTunnel $tunnel $waitForThreadExit]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}


delete_CkSshTunnel $tunnel