我无法使用 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/