Sample code for 30+ languages & platforms
Tcl

SSH Tunnel Through an Outbound SOCKS Proxy

See more SSH Tunnel Examples

Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword properties.

Background: This is the reverse direction from dynamic forwarding: here a SOCKS proxy is used to reach the SSH server, for networks where outbound connections must pass through one. SocksVersion is the switch — 0 means no SOCKS, while 4 or 5 selects the protocol. SOCKS5 supports username/password authentication and remote DNS; SOCKS4 supports only a username.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SshTunnel
#  properties SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword.

set tunnel [new_CkSshTunnel]

#  Set SocksVersion to 4 or 5 to route the outbound connection to the SSH server through a SOCKS
#  proxy.  A value of 0 (the default) means no SOCKS proxy.
CkSshTunnel_put_SocksVersion $tunnel 5
CkSshTunnel_put_SocksHostname $tunnel "socks.example.com"
CkSshTunnel_put_SocksPort $tunnel 1080

#  SOCKS4 supports only a username; SOCKS5 supports username and password.
CkSshTunnel_put_SocksUsername $tunnel "myProxyLogin"
CkSshTunnel_put_SocksPassword $tunnel "myProxyPassword"

CkSshTunnel_put_DestHostname $tunnel "db.internal.example.com"
CkSshTunnel_put_DestPort $tunnel 5432

#  Connect to the SSH server through the SOCKS proxy configured above.
set sshPort 22
set success [CkSshTunnel_Connect $tunnel "ssh.example.com" $sshPort]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

#  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
}

set listenPort 1080
set success [CkSshTunnel_BeginAccepting $tunnel $listenPort]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

puts "Tunnel established through the SOCKS proxy."

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


delete_CkSshTunnel $tunnel