且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python 通过 SSH 隧道连接到远程 PostgreSQL 数据库

更新时间:2022-11-30 08:19:50

您可以尝试使用 sshtunnel 模块,该模块使用 Paramiko 并且与 Python 3 兼容.

You can try using sshtunnel module that uses Paramiko and it's Python 3 compatible.

希望它对你有所帮助...我也挠了一阵子想在 Python 代码中做这件事并避免 SSH 外部隧道,我们需要感谢开发人员将复杂的库包装成简单的代码!

Hopefully it helps you... I scratched myself the head for a while too to do it within Python code and avoid SSH external tunnels, we need to thank developers that wrap complex libraries into simple code!

很简单,从本地端口生成到远程服务器 localhost 中端口 5432 的隧道,然后使用它通过 localhost 连接到远程数据库.

Will be simple, generate a tunnel to port 5432 in localhost of remote server from a local port then you use it to connect via localhost to the remote DB.

这将是您需要的示例工作代码:

This will be a sample working code for your needs:

#!/usr/bin/env python3
import psycopg2
from sshtunnel import SSHTunnelForwarder
import time

with SSHTunnelForwarder(
         ('pluton.kt.agh.edu.pl', 22),
         ssh_password="password",
         ssh_username="aburban",
         remote_bind_address=('127.0.0.1', 5432)) as server:

    conn = psycopg2.connect(database="dotest",port=server.local_bind_port)
    curs = conn.cursor()
    sql = "select * from tabelka"
    curs.execute(sql)
    rows = curs.fetchall()
    print(rows)