title: PyGreSQL/pg hangs when connecting to DB over SSH tunnel
body: <p>In my Python script, I want to be able to connect to a Postgres DB via an SSH tunnel.</p>
  
  <p>I'm using sshtunnel package to create a tunnel, and using PyGreSQL to connect to the DB.
  When I try to establish the database connection, the pg.connect call just hangs. I don't get any errors at all. When I use psql to connect to the DB using the tunnel created by sshtunnel, the connection is successful.</p>
  
  <p>When I create the tunnel beforehand using ssh in shell, pg.connect call successfully connects to the database.</p>
  
  <p>So to summarize:</p>
  
  <ul>
  <li>Tunnel created in Python/sshtunnel  -> pg.connect call hangs</li>
  <li>Tunnel created in Python/sshtunnel -> psql works just fine</li>
  <li>Tunnel created using ssh  -> pg.connect call is successful</li>
  </ul>
  
  <p>This seems to be a problem with PyGreSQL since psql can access the DB using tunnel by sshtunnel just fine. However, there could be something different about the tunnel by sshtunnel package that I'm not seeing.</p>
  
  <p>This is the command I'm using to create the tunnel using SSH:
  <code>ssh -g -L &lt;local_bind_port&gt;:localhost:&lt;remote_bind_port&gt; -f -N root@myip</code></p>
  
  <p>Following is my code to connect to the DB in Python using SSH Tunnel and pg.connect</p>
  
  <pre><code>from sshtunnel import SSHTunnelForwarder
  dbasename = 'db'
  username = 'admin'
  password = 'admin'
  portnum = 5432
  tunnel = SSHTunnelForwarder(
              &lt;ip_address&gt;,
              ssh_username="admin",
              ssh_password="admin",
              remote_bind_address=('127.0.0.1', portnum)
          )
  tunnel.start()
  # The line below hangs
  db = pg.connect(host=tunnel.local_bind_host, port=tunnel.local_bind_port, dbname=dbasename, user=username, passwd=password)
  </code></pre>
  
  <p>Any ideas about what could cause this problem? Are there any logs etc I that might help identify the problem?</p>
  
  <p>Thanks.</p>
  
  <p>EDIT:</p>
  
  <p>It turns out that if I open a tunnel using python/SSHTunnel in one python shell, but use pg.connect to connect to that tunnel in the 2nd python shell it connects successfully.
  So if I copy paste the following in the 1st shell:</p>
  
  <pre><code>from sshtunnel import SSHTunnelForwarder
  dbasename = 'db'
  username = 'admin'
  password = 'admin'
  portnum = 5432
  tunnel = SSHTunnelForwarder(
              &lt;ip_address&gt;,
              ssh_username="admin",
              ssh_password="admin",
              remote_bind_address=('127.0.0.1', portnum)
          )
  tunnel.start()
  </code></pre>
  
  <p>then open another shell and connect to the tunnel from the 1st shell</p>
  
  <pre><code>import pg
  # This works for some reason
  db = pg.connect(host='127.0.0.1', port=&lt;local hind port from the 1st shell&gt;, dbname=dbasename, user=username, passwd=password)
  </code></pre>
  
  <p>the connection is successful</p>