Python 通过 SSH 连接到 Postgres - 端口不正确?

问题描述 投票:0回答:2

我正在尝试通过 ssh 服务器连接到 postgres 数据库。在 postico 上,它可以工作,看起来像这样:

当我从 postico 复制 url 时,它看起来像这样:

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

但是,当我尝试用python实现它时,它成功连接到SSH服务器,但无法成功连接到postgres。

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?

我的代码:

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()
python postgresql ssh psycopg2
2个回答
0
投票

我必须连接到本地主机,因为这是端口转发。


0
投票

我将举一个有效的例子

import psycopg2
from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
    (hostname_ssh, port_ssh),
    ssh_username=username_ssh,
    ssh_pkey=key_filename_ssh,
    remote_bind_address=(ENDPOINT, PORT)
) as tunnel:
    print(f'SSH Tunnel working: Local bind port #{tunnel.local_bind_port}')
    db_connection = psycopg2.connect(
        host='127.0.0.1', 
        port=tunnel.local_bind_port,
        database=DBNAME,
        user=USER,
        password=passcode)
    
    db_cursor = db_connection.cursor()
    # SELECT
    db_cursor.execute('''
                            SELECT COUNT(*)
                            FROM table
                      ''')
    records = db_cursor.fetchall()
    print(records)
    db_cursor.close()
    db_connection.close()
© www.soinside.com 2019 - 2024. All rights reserved.