使用SSHTunnelForwarder通过SSH连接到MySQL数据库

时间:2016-06-23 00:45:43

标签: python mysql ssh mysql-python

我正在尝试通过python中的ssh连接到mysql数据库,但是收到错误。我在python文件'forward.py'中保存了以下内容。我的代码如下:

forward.py

from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
      ('ssh_host', 22),
      ssh_password="ssh_password",
      ssh_username="ssh_username",
      remote_bind_address=('mysql_host', 3306)) as server:

     con = MySQLdb.connect(user='mysql_username',passwd='mysql_password',db='mysql_db_name',host='mysql_host',port=server.local_bind_port)

当我在终端中运行forward.py时,收到以下错误:

_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on     
'mysql_host' (60)")

值得注意的是,这些值是安全性的硬编码值,即'mysql_host'是一个实际的主机,我可以在运行时正常运行

ssh mysql_host

通过终端。根据{{​​3}}

,我也可以使用相同的值使用Sequel Pro连接

有人能指出我正确的方向吗?提前致谢

3 个答案:

答案 0 :(得分:1)

我认为您的问题在于您正在创建本地SSH隧道但尝试直接连接到远程主机,这无法使用SSH隧道。

我相信如果您将连接字符串从host='mysql_host'更改为host='127.0.0.1',您就可以解决问题。

如果查看Sequel Pro实例的调试/连接设置,您将看到正在使用的实际连接命令,并希望确认是这种情况。

有关SSH转发的更多参考资料: http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html

答案 1 :(得分:0)

如果您正在使用SSH隧道转发,则需要连接到“localhost:3306”而不是实际的“mysql-host:3306”。

让我解释一下发生了什么:

  1. 您与SSH建立与远程mysql主机的连接
  2. 您的客户端设置隧道并在本地主机上侦听TCP:3306:localhost:3306
  3. 任何到localhost:3306的流量都将通过SSH隧道透明地重定向到mysql_host:3306。
  4. 尝试在配置中使用“localhost:3306”。 看看here的几个例子,它也可以帮到你。

答案 2 :(得分:0)

我认为问题在于您没有指定 local_bind_address。出于这个原因,隧道被分配到您的本地主机端口 60。MySQL 无法从该端口连接。

使用 SSHTunnelForwarder() 函数的 local_bind_address 参数指定 local_bind_address 端口。

相关问题