通过EC2 Jumphost(SSH)将psycopg2连接到专用RDS

时间:2020-09-09 16:02:15

标签: amazon-ec2 ssh amazon-rds

我正在通过EC2 Jumphost通过SSH连接将python脚本连接到我的RDS中,该EC2出现多个问题。这似乎是最接近的工作方式,但我仍然不知道下一步该怎么做。

提供的错误是'OperationalError:无法连接到服务器: 操作超时服务器在主机xxx(xxx)和 在端口xxxx上接受TCP / IP连接?

 from sshtunnel import SSHTunnelForwarder 
 import psycopg2

  with SSHTunnelForwarder(
    ('xxxx.us-east-2.compute.amazonaws.com'),
    ssh_username="username",
    ssh_pkey="jump_host.pem",
    remote_bind_address=('xxx.us-east-2.rds.amazonaws.com', 15432) ) as tunnel:
    print("****SSH Tunnel Established****")
 
    db = psycopg2.connect(dbname='postgres', user='user', password='password', host='xxx.us-east-2.rds.amazonaws.com', port=tunnel.local_bind_port)
    # Run sample query in the database to validate connection
    try:
        # Print all the databases
        with db.cursor() as cur:
            cur.execute('SHOW DATABASES')
            for r in cur:
                print(r)
    finally:
        db.close()   

我可以使用的是key.pem,EC2 IP地址/端口,jumphost的用户名,数据库;主机,端口,dbname,用户名,密码。 IP地址已列入白名单,我可以使用上述所有方法通过DBeaver访问信息。

我尝试将paramiko与存储为的键一起使用:

mypkey = paramiko.RSAKey.from_private_key_file('jump_host.pem')

以及sshtunnel提供的示例,该示例具有以下错误:

BaseSSHTunnelForwarderError:无法建立与SSH的会话 网关

with SSHTunnelForwarder(
    ('3.129.XXX.XXX', 443),
    ssh_username="username",
    ssh_pkey=mypkey,
    ssh_private_key_password="",
    remote_bind_address=('3.129.XXX.XXX', 22),
    local_bind_address=('0.0.0.0', 10022)
) as tunnel:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('127.0.0.1', 10022)
    # do some operations with client session
    client.close()

print('FINISH!')

我应该如何最好地设置一个Python脚本以SSH进入EC2,连接到私有RDS,然后运行所需的所有代码?

谢谢!

0 个答案:

没有答案