psycopg2 和 postgresql 的远程连接问题

Remote connection issues with psycopg2 and postgresql

我正在尝试使用以下 python 代码连接到 postgresql 数据库:

try:
    conn = psycopg2.connect("host = '10.47.65.237' dbname = 'testDB' user = 'pi' password = 'raspberry'")
except:
    print("Unable to connect to testDB at 10.47.65.237. Sending Alert.")

此代码适用于 localhost 127.0.0.1,但是当我转到另一台机器并尝试 运行 使用上面的 ip 时,它无法连接。

我做过的事情: 1. 5432端口开放 2. 通过添加行 "listen_addresses='10.47.65.138'" 编辑 postgresql.conf 3. 编辑pg_hba.conf 添加如下配置"host all all 10.47.65.138 md5"

还有其他我可以尝试或遗漏的事情吗?

运行 telnet 10.47.65.237 5432 在客户端应该会导致 Connection Refused 错误,这表明问题与 psycopg2 无关。

您错误配置了服务器。 listen_addresses controls which IPs the server will answer on, not which IPs the server will permit connections from. 您服务器的 postgresql.conf 应该有 listen_addresses='10.47.65.237'listen_addresses='*'。编辑配置并在服务器上重新启动 PostgreSQL,然后您应该能够使用 telnet 和 psycopg2.

成功连接