【发布时间】: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