【问题标题】:Can't connect to postgres server over SSH through python无法通过 python 通过 SSH 连接到 postgres 服务器
【发布时间】:2018-08-14 22:26:24
【问题描述】:

我正在尝试通过 SSH 连接到服务器并连接到在其上运行的 postgres 实例。我可以通过 SSH 连接到服务器并通过 termianl 访问 postgres 服务器,并且 pg_settings 中的端口是 5432。如果有任何区别,在使用 SSH_USER SSH 进入服务器后,我必须切换用户('sudo su - postgres')。

错误:

psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

代码:

SSH_HOST = 'xxx.xxx.xxx.xxx'
SSH_FOREIGN_PORT = 22
SSH_USER = 'user1'
SSH_PASS = 'pass'
PORT = 5432
DBNAME = 'testdb'
USER = 'postgres'
PASS = ''

def main_psql():
    #try:
    with SSHTunnelForwarder((SSH_HOST, SSH_FOREIGN_PORT), ssh_username=SSH_USER, ssh_password=SSH_PASS, remote_bind_address=('localhost', PORT)) as server:
        server.start()
        cnx = psycopg2.connect(dbname=DB_NAME, user=USER, password=PASS)

编辑:错误 2:

File "/Users/me/PycharmProjects/proj/src/import_psql.py", line 285, in main_psql
  cnx = psycopg2.connect(dbname=DB_NAME, user=USER, password=PASS, host='localhost', port=PORT) #, host='/var/run/postgresql')
File "/Users/me/PycharmProjects/proj/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect
  conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

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

如果我通过终端在 SSH'g 之后从 postgres 用户运行 netstat,我会得到:

-bash-4.2$ netstat -nl |grep 5432
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN     
tcp6       0      0 :::5432                 :::*                    LISTEN     
unix  2      [ ACC ]     STREAM     LISTENING     26541    /var/run/postgresql/.s.PGSQL.5432
unix  2      [ ACC ]     STREAM     LISTENING     26543    /tmp/.s.PGSQL.5432

【问题讨论】:

    标签: postgresql python-2.7 ssh ssh-tunnel


    【解决方案1】:

    您必须在psycopg2.connect(dbname=DB_NAME, user=USER, password=PASS, host=..., port=...) 中指定 HOST 和 PORT。 默认情况下,postgres 客户端连接到 Unix 域套接字而不是 TCP 套接字。

    【讨论】:

    • 如果我将主机指定为 localhost 并将端口指定为 5432(我认为这是正确的),我会收到以下错误(添加到主帖)。
    • 然后在 bash 中测试你的 ssh 隧道。 SSHTunnelForwarder 库可能有问题。创建一个隧道并从终端使用标准 psql 连接到它。
    猜你喜欢
    • 2019-10-19
    • 2017-07-17
    • 1970-01-01
    • 2020-11-02
    • 2018-07-20
    • 2013-04-09
    • 2016-07-15
    • 2021-05-09
    • 2017-02-09
    相关资源
    最近更新 更多