python - 以 postgres 用户身份连接到 PostgreSQL 时出现连接错误?

标签 python postgresql psycopg2

我无法使用 python 和 psycopg2 远程连接到 PostgreSQL:

这是我的代码。

>>> import psycopg2
>>> conn_string = "host='localhost' dbname='mydb' user='postgres'"
>>> print "Connecting to database\n     ->%s" % (conn_string)
    Connecting to database
      ->host='localhost' dbname='mydb' user='postgres'
>>> conn = psycopg2.connect(conn_string)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tools/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

无法连接到服务器:连接被拒绝 服务器是否在主机“localhost”(127.0.0.1)上运行并接受 端口 5432 上的 TCP/IP 连接?

没有为 postgres 用户设置密码。

通常,我可以通过在主机上运行以下方法来连接数据库。

 1. SSH to box
 2. su - postgres
 3. psql
 4. \c mydb

服务器运行 PostgreSQL 9.1。

最佳答案

您正在尝试使用计算机上运行的脚本连接到 localhost 上的 PostgreSQL,但那里没有运行 PostgreSQL 服务器。

为此,您必须通过 ssh 连接到远程服务器,然后在那里运行 Python 脚本,其中 PostgreSQL 服务器相对于 Python 脚本而言是“本地”服务器。

(这就是运行 psql 有效的原因 - 因为您在远程服务器上运行它,其中 PostgreSQL 相对于 psql 是“本地”的>).

或者,您可以:

  • 使用 SSH 隧道将 PostgreSQL 端口从本地计算机转发到远程计算机;或

  • 在服务器上启用远程连接后,使用主机名或 IP 地址通过 TCP/IP 直接连接到远程 PostgreSQL 服务器。

请注意,仅将服务器的 IP 地址或主机名而不是 localhost 放入连接字符串将不起作用,除非您还将服务器配置为接受远程连接。您必须设置listen_addresses以监听非本地连接,添加任何所需的防火墙规则,设置pg_hba.conf以允许来自远程计算机的连接,并且最好设置SSL。所有这些都在 PostgreSQL 用户手册的客户端身份验证一章中进行了介绍。

您可能会发现 SSH 隧道更简单、更容易理解。

关于python - 以 postgres 用户身份连接到 PostgreSQL 时出现连接错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26034092/

相关文章:

java - 是否可以在没有列的情况下在 JPA/Hibernate 中创建和使用序列生成器?

ruby - rake 数据库 :migrate runs into an error for an undefined method

python - 错误 psycopg2.OperationalError : fe_sendauth: no password supplied even after postgres authorized connection

python - 将空格分隔的整数求和为列表中的字符串

python - 基于客户端IP地址的 Pyramid 授权

python - 如何将多个csv文件导入MongoDB?

sqlalchemy - psycopg2.操作错误: could not translate host name "<address>" to address: Temporary failure in name resolution

python - 将具有 NaN 的多列 Pandas 数据框转换为嵌套字典

python - 使用 Python 连接到 Amazon RDS Postgresql 数据库时出错

python - psycopg2 - 如何将 NULL 类型更改为字符串 'NA' 而不是 None