简体   繁体   English

通过 Python 中的 SSH 连接到 Postgres DB 的问题

[英]Issues with connecting to Postgres DB via SSH in Python

I've been given a postgres DB in my uni project in which I have to SSH into the network from which I can then access the DB.我在我的 uni 项目中获得了一个 postgres 数据库,我必须将 SSH 连接到网络中,然后我可以从中访问数据库。 I've set up the connection in DBeaver using the SSH tab and it works perfectly fine.我已经使用 SSH 选项卡在 DBeaver 中设置了连接,它工作得非常好。 However, using Python, I can connect to the SSH just fine, but cannot connect to the DB itself.但是,使用 Python,我可以很好地连接到 SSH,但无法连接到数据库本身。 I've checked with another DB that doesn't require SSH and that works just fine.我检查了另一个不需要 SSH 的数据库,效果很好。 Here is my code.这是我的代码。 Note: I've already tried using SSHTunnel, too, to no avail.注意:我也已经尝试过使用 SSHTunnel,但无济于事。 Also, ignore my quick hack to anonymize my SSH login data, as I didn't find how to use a proper config file with paramiko late at night yesterday...另外,请忽略我的快速破解以匿名化我的 SSH 登录数据,因为昨天深夜我没有找到如何使用 paramiko 的正确配置文件...

import os
from psycopg2 import connect, Error
from paramiko import SSHClient
from config import config

with open("ssh_config.txt", "r") as f:
    lines = f.readlines()
    hostname = lines[0].strip()
    username = lines[1].strip()
    password = lines[2].strip()

ssh = SSHClient()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect(hostname=hostname, username=username, password=password)
print("SSH connected.")

try:
    params = config()
    conn = connect(**params)
    cursor = conn.cursor()
    print("DB connected.")
    # Print PostgreSQL connection properties.
    print(conn.get_dsn_parameters(), "\n")

    # Print PostgreSQL version.
    cursor.execute("SELECT version();")
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)

Any help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

I've figured it out myself.我自己想通了。 Here is the updated code.这是更新的代码。 Basically, I had to forward the remote address to localhost and then connect to localhost instead of the DB address.基本上,我必须将远程地址转发到 localhost,然后连接到 localhost 而不是 DB 地址。

from psycopg2 import connect, Error
from sshtunnel import SSHTunnelForwarder
from config import config

with open("ssh_config.txt", "r") as f:
    lines = f.readlines()
    hostname = lines[0].strip()
    username = lines[1].strip()
    password = lines[2].strip()
    remote_bind_address = lines[3].strip()

try:
    with SSHTunnelForwarder(
        (hostname, 22),
        ssh_username=username,
        ssh_password=password,
        remote_bind_address=(remote_bind_address, 5432),
        local_bind_address=("localhost", 8080)) \
            as tunnel:

        tunnel.start()
        print("SSH connected.")

        params = config()
        conn = connect(**params)
        cursor = conn.cursor()
        print("DB connected.")
        # Print PostgreSQL connection properties.
        print(conn.get_dsn_parameters(), "\n")

        # Print PostgreSQL version.
        cursor.execute("SELECT version();")
        record = cursor.fetchone()
        print("You are connected to - ", record, "\n")
        cursor.close()
        conn.close()
        tunnel.close()
        print("DB disconnected.")
except (Exception, Error) as error:
    print("Error while connecting to DB", error)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM