简体   繁体   English

在Windows上使用Python通过SSH连接数据库时出错

[英]Error connecting to DB via ssh with Python on Windows

I have a snippet of code that allows me to connect to my psql DB via ssh in Python. 我有一小段代码,可让我通过Python中的ssh连接到我的psql DB。 It works perfectly on Ubuntu 18.10 (via VirtualBox) but fails every time on windows with an error that it can't reach the remote host and port. 它可以在Ubuntu 18.10上完美运行(通过VirtualBox),但每次在Windows上均会失败,并显示无法到达远程主机和端口的错误。

I'm been developing a user interface that can query data from a remote DB (logs etc.) and visualize it. 我正在开发一个用户界面,该用户界面可以查询远程数据库中的数据(日志等)并将其可视化。

All of the development has been done using Spyder3 on Ubuntu 18.10. 所有开发工作均已在Ubuntu 18.10上使用Spyder3完成。 I never had an issue until I tried to execute the same code on Windows 10. 在尝试在Windows 10上执行相同的代码之前,我从未遇到过任何问题。

I tried Telnet to both the localhost:port and remote host:port (via ssh) and it works. 我尝试通过Telnet到localhost:port和远程host:port(通过ssh),并且可以正常工作。 Having looked up all the possible answers on stackoverflow and other places, I still haven't been able to fix the issue. 在stackoverflow和其他地方查找了所有可能的答案后,我仍然无法解决该问题。 The fact that it works on one environment and not on the other, while on the same machine, tells me it's some sort of environment setting but I don't know what it could be. 它可以在一个环境上运行,而不能在同一台计算机上在另一个环境上运行,这一事实告诉我这是某种环境设置,但我不知道它可能是什么。

The code: 编码:

import psycopg2
import logging
logging.basicConfig(level=logging.DEBUG)

from sshtunnel import SSHTunnelForwarder

PORT = 5432
REMOTE_HOST = '111.222.111.222'
REMOTE_SSH_PORT = 22
curs = None
conn = None


server = SSHTunnelForwarder((REMOTE_HOST, REMOTE_SSH_PORT),
     ssh_username='username',
     ssh_password='password',
     remote_bind_address=('localhost', PORT),
     local_bind_address=('localhost', PORT))

server.start()
conn = psycopg2.connect(database='db_name', user='db_username', password='db_password', host='127.0.0.1', port='5432')
curs = conn.cursor()

Expected: A successful connection to ssh and subsequent successful log-in to the database. 预期:与ssh的成功连接以及随后成功登录到数据库。 This works on Ubuntu 18.10 via VirtualBox on the same machine. 这可以通过同一台计算机上的VirtualBox在Ubuntu 18.10上运行。

Actual result: 2019-01-02 10:54:51,489 ERROR Problem setting SSH Forwarder up: Couldn't open tunnel localhost:5432 <> localhost:5432 might be in use or destination not reachable 实际结果:2019-01-02 10:54:51,489错误设置SSH转发器时出现问题:无法打开隧道localhost:5432 <> localhost:5432可能正在使用中或无法访问目标

I may be wrong, but I think the remote_bind_address should be set to your server's private IP. 我可能是错的,但是我认为remote_bind_address应该设置为服务器的专用IP。 As this is where the remote machine would communicate to your machine. 因为这是远程计算机与您的计算机进行通信的地方。

 remote_bind_address=(<PRIVATE_SERVER_IP>, PORT)

我意识到我的本地postgres(psql)服务正在干扰端口映射,因为它也正在使用端口5432。一旦我禁用了该服务,它就像一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM