Connecting to PostgreSQL database through SSH tunneling in Python
<p>I am trying to connect to a server remotely and then access it's local database with Python. I am successfully connecting to the server, although I can't seem to connect to the database on the server. My code is below:</p>
<pre><code>import psycopg2
from sshtunnel import SSHTunnelForwarder

try:

    with SSHTunnelForwarder(
         ('&lt;server ip address&gt;', 22),
         ssh_private_key=&quot;&lt;/path/to/private/ssh/key&gt;&quot;,
         ssh_username=&quot;&lt;server username&gt;&quot;,
         remote_bind_address=('localhost', 5432)) as server:

        print &quot;server connected&quot;
        
        conn = psycopg2.connect(database=&quot;&lt;dbname&gt;&quot;,port=server.local_bind_port)
        curs = conn.cursor()
        print &quot;database connected
    
except:
    print &quot;Connection Failed&quot;
</code></pre>
<p>These are pieces of code I have found on the internet and pieced together. I have also tried the connection statements below in place of the code above:</p>
<pre><code>params = {
  'database': '&lt;dbname&gt;',
  'user': '&lt;dbusername&gt;',
  'password': '&lt;dbuserpass&gt;',
  'host': 'localhost',
  'port': 5432
}
conn = psycopg2.connect(**params)
</code></pre>
<p>I know I can connect to the database because on my machine; I am able to use <code>sqlectron</code> to tunnel in and connect appropriately.</p>
<p>Just in case it is not clear what I am trying to do from above, I need to ssh tunnel into my remote server using a private ssh key on my computer (working properly), and then I need to connect to a PostgreSQL database that is on <code>localhost</code> at port <code>5432</code>.</p>
<p>I am currently getting the current error message for both ways of trying to connect:</p>
<pre class="lang-none prettyprint-override"><code>2016-01-23 11:16:10,978 | ERROR   | Tunnel: 0.0.0.0:49386 &lt;&gt; localhost:5432 error: (9, 'Bad file descriptor')
</code></pre>