【发布时间】:2016-04-30 04:21:50
【问题描述】:
我正在尝试远程连接到服务器,然后使用 Python 访问它的本地数据库。我成功连接到服务器,虽然我似乎无法连接到服务器上的数据库。我的代码如下:
import psycopg2
from sshtunnel import SSHTunnelForwarder
try:
with SSHTunnelForwarder(
('<server ip address>', 22),
ssh_private_key="</path/to/private/ssh/key>",
ssh_username="<server username>",
remote_bind_address=('localhost', 5432)) as server:
print "server connected"
conn = psycopg2.connect(database="<dbname>",port=server.local_bind_port)
curs = conn.cursor()
print "database connected
except:
print "Connection Failed"
这些是我在互联网上找到并拼凑起来的代码片段。我还尝试了下面的连接语句来代替上面的代码:
params = {
'database': '<dbname>',
'user': '<dbusername>',
'password': '<dbuserpass>',
'host': 'localhost',
'port': 5432
}
conn = psycopg2.connect(**params)
我知道我可以连接到数据库,因为在我的机器上;我可以使用sqlectron 进行隧道连接并正确连接。
以防万一不清楚我要从上面做什么,我需要使用我计算机上的私有 ssh 密钥通过 ssh 隧道进入我的远程服务器(正常工作),然后我需要连接到 PostgreSQL位于localhost 端口5432 上的数据库。
我目前收到两种尝试连接方式的当前错误消息:
2016-01-23 11:16:10,978 | ERROR | Tunnel: 0.0.0.0:49386 <> localhost:5432 error: (9, 'Bad file descriptor')
【问题讨论】:
标签: python database postgresql ssh ssh-tunnel