【问题标题】:Not able to connect to EC2 instance in AWS via python/psycopg2无法通过 python/psycopg2 连接到 AWS 中的 EC2 实例
【发布时间】:2022-01-24 18:37:25
【问题描述】:

我无法通过 python 连接到 aws。我有一个 macOSX 操作系统。

我做了什么:

  1. 我创建了一个 ec2 实例并选择了一个操作系统 (ubuntu) 并在远程服务器中下载了 postgresssql。然后我创建了安全组,在其中添加了以下配置: 类型: SSH 协议: tcp 端口:22 来源:自定义,0.0.0.0/0

然后我添加了另一个规则: PostgreSQL TCP 5432 风俗 my_computer_ip_address 71.???.??.???/32

我添加问号只是为了隐藏地址。但它是那种格式。

现在,aws 让我创建了一个 .pem 文件,以便从数据库中查询。我将此 pem 文件下载到了一个秘密位置。
当我去我的本地机器时,去我的终端并输入: ssh -i "timescale.pem" ubuntu@ec2-??-???-??-???.compute-1.amazonaws.com"

我可以连接。我还去了我的 dbeaver 并创建了一个新连接并设置了一个连接,我使用 ssh 隧道和公钥来读取我创建的“timescale.pem”文件。然后我转到 main 并输入我的用户名和密码: 用户名:postgres 数据库:示例 密码:mycustompassword

我可以毫无问题地连接。

现在,当我使用 psycopg2 库访问 python 时,我根本无法连接。我已经浏览了*中的所有示例,但没有一个对我有帮助。这是我用来从 python 连接到 aws 的内容:

path_to_secret_key = os.path.expanduser("~/timescale.pem")
conn = psycopg2.connect(
    dbname='example',
    user='postgres',
    password='pass123',
    host='ec2-??-??-??-???.compute-1.amazonaws.com',
    port='22',
    sslmode='verify-full',
    sslrootcert=path_to_secret_key)

然后我得到这个错误:

connection to server at "ec2-34-???-??-???.compute-1.amazonaws.com" (34.201.??.???), port 22 failed: could not read root certificate file "/Users/me/timescale.pem": no certificate or crl found

好的...然后我切换了端口并添加了“5432”并收到此警告:

connection to server at "ec2-??-???-??-???.compute-1.amazonaws.com" (34.???.??.212), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?

当我 ssh 进入我的终端并输入:netstat -nl |grep 5432 我得到以下信息:

tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN     

unix 2 [ACC] STREAM LISTENING 812450 /var/run/postgresql/.s.PGSQL.5432

有人可以帮忙吗?谢谢

【问题讨论】:

    标签: python-3.x amazon-web-services amazon-ec2 psycopg2


    【解决方案1】:

    .pem 文件用于通过 SSH 在端口 22 上连接到 EC2 实例。 PostgreSQL 在端口 5432 上运行。您不将.pem 文件用于数据库连接,仅用于ssh 连接。您需要更改 Python 脚本以使用 port='5432', 直接连接到 EC2 实例上运行的 PostgreSQL 服务。

    【讨论】:

      【解决方案2】:

      这似乎现在可以工作了:

      from sshtunnel import SSHTunnelForwarder
      mypkey = paramiko.Ed25519Key.from_private_key_file(path_to_secret_key)
      tunnel = SSHTunnelForwarder(
          ('remote_public_port', 22),
          ssh_username='ubuntu',
          ssh_pkey=mypkey,
          remote_bind_address=('localhost', 5432))
      tunnel.start()
      
      conn = psycopg2.connect(
          dbname='example_db',
          user='postgres',
          password='secret123',
          host='127.0.0.1',
          port=tunnel.local_bind_port)
      

      【讨论】:

        最近更新 更多