Python Connection to Postgres over SSH- Incorrect port?

Question:

I am trying to connect to a postgres database over an ssh server. On postico, it works, and looks something like this:

enter image description here

When I copy the url from postico, it looks like this:

postgresql+ssh://[email protected]/exampleusername:[email protected]/exampledb

However, when I try to implement it in python, it connects successfully to the SSH server, but cannot connect to the postgres successfully.

psycopg2.OperationalError: connection to server at "example-rds-host.com" (X.X.X.X), port 56804 failed: Operation timed out
    Is the server running on that host and accepting TCP/IP connections?

My code:

ssh_tunnel = SSHTunnelForwarder(
        (“example-ec2-host.com”, 22),
        ssh_username="ubuntu",
        ssh_private_key= ‘xRedactedx/Desktop/examplekey’,
        remote_bind_address=(“example-rds-host.com”, 5432)
    )
ssh_tunnel.start()
conn_string = "host='{}' dbname='{}' user='{}' password='{}' sslmode='{}' port='{}'".format(host, “exampledb” , ”exampleusername” ,”examplepassword”, ssl_mode, ssh_tunnel.local_bind_port)
self.connection = psycopg2.connect(conn_string)
self.cursor = self.connection.cursor()
Asked By: Jason Chan

||

Answers:

I have to connect to localhost, since this is a port forward.

Answered By: Jason Chan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.