使用 Python Paramiko 通过双 SSH 隧道连接到数据库

Connect to database through double SSH tunnel using Python Paramiko

这是我的 ssh 命令,它通过堡垒主机代理与 Postgres 数据库建立隧道 -

ssh -i C:/public/keys/my_key.pem -o "ProxyCommand ssh -W %h:%p username1@bastion_host.com" username2@ssh_host_ip -N -L 12345:postgres_host.com:5432 ssh_host_ip

我想使用 sshtunnel 实用程序将其转换为 Python 脚本。但是很难弄清楚要在实用程序中传递什么,如图所示:

我在 Stack Overflow 上浏览了几篇文章,但没有找到一种直接的方法。开发人员正在使用代理转发作为 Proxy 命令的解决方案。将上述命令直接转换为 sshtunnel 或 Paramiko 或任何其他 pythonic 方式将非常有帮助。

基于Connecting to PostgreSQL database through SSH tunneling in Python,应执行以下操作:

with SSHTunnelForwarder(
        'bastion_host',
        ssh_username="username1", ssh_password="password1",
        remote_bind_address=('ssh_host_ip', 22)) as bastion:
        
    bastion.start()
    
    with SSHTunnelForwarder(
            ('127.0.0.1', bastion.local_bind_port),
            ssh_username="username2", ssh_pkey="C:/public/keys/my_key.pem",
            remote_bind_address=('postgres_host', 5432)) as ssh:

        ssh.start()

        engine = create_engine(
            'postgresql://<db_username>:<db_password>@127.0.0.1:' +
            str(ssh.local_bind_port) + '/database_name')