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

时间:2018-03-06 22:56:51

标签: postgresql python-2.7 ssh ssh-tunnel

我尝试通过SSH连接到服务器并连接到在其上运行的postgres实例。我可以通过termianl SSH进入服务器并访问postgres服务器,pg_settings中的端口为5432。如果它有任何区别,在SSH使用SSH_USER进入服务器之后我必须切换用户(' 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

1 个答案:

答案 0 :(得分:0)

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