Sample code for 30+ languages & platforms
CkPython

Close an SSH Tunnel

See more Socket/SSL/TLS Examples

Demonstrates Socket.SshCloseTunnel, which closes the SSH tunnel opened by SshOpenTunnel and terminates its forwarded channels.

Background. Closing the tunnel does not affect unrelated SSH objects or connections.

Chilkat CkPython Downloads

CkPython
import sys
import chilkat

success = False

socket = chilkat.CkSocket()

#  Connect to the SSH server and initialize an SSH tunneling session.  Port 22 is conventional but
#  not required.
success = socket.SshOpenTunnel("ssh.example.com",22)
if (success == False):
    print(socket.lastErrorText())
    sys.exit()

#  Authenticate the SSH session before opening forwarded channels.
#  The SSH password should come from a secure source rather than being hard-coded.
sshPassword = "mySshPassword"
success = socket.SshAuthenticatePw("sshUser",sshPassword)
if (success == False):
    print(socket.lastErrorText())
    sys.exit()

#  Close the SSH tunnel and terminate its forwarded channels.  This does not affect unrelated SSH
#  objects or connections.
success = socket.SshCloseTunnel()
if (success == False):
    print(socket.lastErrorText())
    sys.exit()

print("SSH tunnel closed.")