Sample code for 30+ languages & platforms
Tcl

Close an SSH Tunnel (CloseTunnel)

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops the tunnel-manager thread. The only argument (waitForThreads) selects whether to wait for the worker threads to exit.

Background: This is the full shutdown — it stops the listener, disconnects clients, and ends the background threads, so it is what you call when the tunnel is no longer needed. Passing true for waitForThreads makes the call block until the workers have actually exited, which matters before the program terminates or reuses the object; if a worker fails to stop, the method returns false and LastErrorText explains why.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates the SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops
#  the tunnel-manager thread.  The only argument (waitForThreads) selects whether to wait for the
#  worker threads to exit.

set tunnel [new_CkSshTunnel]

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

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
}

#  ... the tunnel runs ...

#  Shut everything down: disconnect clients and stop the tunnel-manager thread.  With
#  waitForThreads 1, the method waits for the worker threads to exit.
set waitForThreads 1
set success [CkSshTunnel_CloseTunnel $tunnel $waitForThreads]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

puts "Tunnel closed."

delete_CkSshTunnel $tunnel