【发布时间】:2020-05-22 04:45:54
【问题描述】:
在我的 uni 项目中,我获得了一个 postgres 数据库,我必须通过 SSH 连接到网络,然后我才能访问该数据库。我已经使用 SSH 选项卡在 DBeaver 中建立了连接,它工作得非常好。但是,使用 Python,我可以很好地连接到 SSH,但无法连接到数据库本身。我检查了另一个不需要 SSH 的数据库,它工作得很好。这是我的代码。注意:我也已经尝试过使用 SSHTunnel,但无济于事。另外,请忽略我的快速破解以匿名化我的 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)
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: python postgresql ssh