1

I am trying to use Python to connect to a PostgreSQL instance, which is located on Azure through an SSH tunnel. I can connect to the database with DBeaver with no Problem. Here is the code that I am using.

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    ('160.**.**.**', 22),
    ssh_username="*******",
    ssh_password="*******",
    remote_bind_address=('localhost', 5432))

server.start()
print("server connected")

params = {
    'database': '*******',
    'user': '*****postgresadmin@*****dev-postgres',
    'password': '************',
    'host': '**********-postgres.postgres.database.azure.com',
    'port': server.local_bind_port
}

conn = psycopg2.connect(**params)
cur = conn.cursor()

text = "select * from table"
cur.execute(text)

However I get the following error:

conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "**********-postgres.postgres.database.azure.com" to address: Unknown host

I also tried sqlalchemy using this with the same result. Any idea on what I am doing wrong? Do I maybe need the IP-address of the host instead of the domain?

1 Answer 1

1

The SSHTunnelForwarder is used if you want to do some stuff on the remote server.

Another code block is needed if you need to use remote server as a bridge to connect to another server:

import sshtunnel

with sshtunnel.open_tunnel(
    (REMOTE_SERVER_IP, 443),
    ssh_username="",
    ssh_password="*******",
    remote_bind_address=(AZURE_SERVER_HOST, 22),
    local_bind_address=('0.0.0.0', 10022)
) as tunnel:
    params = {
        'database': '*******',
        'user': '*****postgresadmin@*****dev-postgres',
        'password': '************',
        'host': '127.0.0.1',
        'port': 10022
    }

    conn = psycopg2.connect(**params)
    cur = conn.cursor()

    text = "select * from table"
    cur.execute(text)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.