【问题标题】:Python: Connect to an Azure PostgreSQL instance through SSH TunnelPython:通过 SSH 隧道连接到 Azure PostgreSQL 实例
【发布时间】:2021-05-31 16:26:52
【问题描述】:

我正在尝试使用 Python 连接到 PostgreSQL 实例,该实例通过 SSH 隧道位于 Azure 上。我可以毫无问题地使用 DBeaver 连接到数据库。 这是我正在使用的代码。

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)

但是我收到以下错误:

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

我还使用this 尝试了sqlalchemy,结果相同。 知道我做错了什么吗?我可能需要主机的 IP 地址而不是域吗?

【问题讨论】:

    标签: python postgresql azure ssh


    【解决方案1】:

    如果您想在远程服务器上做一些事情,则使用 SSHTunnelForwarder。

    如果您需要使用远程服务器作为桥接器连接到另一台服务器,则需要另一个代码块:

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2014-03-21
      • 2013-05-26
      • 2021-11-13
      • 2021-12-02
      • 2015-03-01
      • 2017-03-04
      相关资源
      最近更新 更多