Search code examples
pythonssh-tunnel

How to set connection timeout to sshtunnel


I use SSHTunnelForwarder from sshtunnel module on python.

Given the next code:

server = SSHTunnelForwarder(
    (sshServer, sshPort),
    ssh_username=sshUsername,
    ssh_password=sshPassword,
    remote_bind_address=(imapServer, imapPort),
    local_bind_address=('127.0.0.1', localPort)
)

print('STARTING')

server.start()

print(server.is_active)

Sometimes it take really long time, maybe few minutes, and then I get error:

2019-04-22 22:25:54,365| ERROR   | Could not connect to gateway ip..... : 110
Traceback (most recent call last):
  File "PYTHON_TUNNEL.py", line 24, in <module>
    server.start()
  File "/home/mike/.local/lib/python2.7/site-packages/sshtunnel.py", line 1295, in start
    reason='Could not establish session to SSH gateway')
  File "/home/mike/.local/lib/python2.7/site-packages/sshtunnel.py", line 1101, in _raise
    raise exception(reason)
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

Ubuntu 18.04, python 2.7

Is it possible to set timeout for tunnel establishment ?


Solution

  • There's an SSH_TIMEOUT constant with a default of None in sshtunnel.py that is set on the socket used to create the transport before calling connect on it.

    Unfortunately, I can't test this myself, but you could try patching that constant before starting the tunnel forwarder:

    import sshtunnel
    
    sshtunnel.SSH_TIMEOUT = 5.0
    
    server = sshtunnel.SSHTunnelForwarder([...])    
    server.start()
    

    There's also a TUNNEL_TIMEOUT constant, but that seems to be used for checks if the tunnel is already established and for the call to open_channel on the underlying Paramiko Transport instance. It does not seem to play a role during the creation of the tunnel.
    Plus, TUNNEL_TIMEOUT is set to one second by default, and with you experiencing minute-long delays on server.start() before the BaseSSHTunnelForwarderError is raised, it seems unlikely that this constant is relevant for a solution to your issue.