SSH隧道可以在终端上运行,但不能在Python上运行?

时间:2019-10-21 04:38:24

标签: python sql ssh ssh-tunnel

我尝试使用以下代码从计算机终端到服务器的SSH隧道。

ssh -L 3306:192.168.0.xx:41xx -p 2220 root@xxx.85.63.xxx

然后我使用以下命令访问(MySQL)内部的数据库。

mysql -u username -h 192.168.0.xx -P 41xx -p

它奏效了。但是当我尝试使用python执行它时,我无法使其工作。我总是遇到以下错误。

OperationalError: (1045, "Access denied for user 'username'@'localhost' (using password: YES)")

到目前为止,我的代码如下。

from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
         ('xxx.85.63.xxx', 2220),
         ssh_password="psswd",
         ssh_username="root",
         remote_bind_address=('192.168.0.xx', 41xx)) as server:

    conn = MySQLdb.connect(host='localhost',
                           port=server.local_bind_port,
                           user='username',
                           passwd='passwd',
                           db='dbname')

我要做的是访问服务器内部的数据库,并执行通常的数据库操作过程。

说实话,我对SSH或SSH隧道并不是很熟悉,所以我在这里很迷路。有人可以指出我应该做什么吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

我相信您已经正确设置了端口转发。

这是一个MySQL权限问题,由“访问被拒绝”指示。

MySQL根据user @ host分配权限。您以用户名@localhost连接,而用户可能仅设置为用户名@ 192.168.0.xx。

要查看我是否正确,请登录SSH主机时try mysql -u username -h localhost -P 41xx -p。我认为它可能不会让您进入。

我将使用SHOW GRANTS FOR 'username'@'localhost';和授予用户名@localhost或用户名@%的GRANT特权,或删除限制性许可。

祝你好运。

相关问题