无法通过python通过SSH连接到postgres服务器

问题描述 投票:0回答:1

我正在尝试通过SSH连接到服务器并连接到在其上运行的postgres实例。我可以通过termianl SSH到服务器并访问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个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.