Python使用SSHTunnelForwarder和MySQLdb连接到MySQL服务器

时间:2016-06-21 10:46:42

标签: python ssh

我想知道如何使用SSH连接到远程MySQL服务器。

    from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
        ('192.168.0.60', 22),
        ssh_password="MySSHPASSWORD",
ssh_username="MUSSHUserName",
remote_bind_address=('192.168.0.30', 3306)) as server:

    conn = MySQLdb.connect(user='UserNameOnSQLSERVER', passwd='PasswordOnSQLSERVER', host='192.168.0.60', db='myDB',
                           port=server.local_bind_port)

我已经能够通过上面的配置连接到这个服务器抛出MySQL Workbench并运行查询,一切运行良好

问题在于,当我尝试通过上面的代码连接此数据库时,我不断收到错误:

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

我还尝试将MySQLdb.connect中的ip更改为

        conn = MySQLdb.connect(user='kiboUser', passwd='Lb24@db30#kL68', host='192.168.0.60', db='dbKiboDashboard',
                           port=server.local_bind_port)

我收到以下错误:

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

请有人帮我理解我做错了什么

由于

1 个答案:

答案 0 :(得分:2)

remote_bind_address是您要进入隧道的那个。确保验证正在侦听的服务器的TCP端口。 要验证这一点,您可以尝试命令

  

netstat的

  

netstat -tln

这应该有效:

with SSHTunnelForwarder(
    ('ServerIP', sshport), #The server's IP and SSH port
    ssh_password="MySSHPASSWORD",
    ssh_username="MUSSHUserName",
    remote_bind_address=('127.0.0.1', 3306)) as server: #The server's TCP IP and port, you're tunneling

conn = MySQLdb.connect(user='UserNameOnSQLSERVER', passwd='PasswordOnSQLSERVER', host='127.0.0.1',
                       port=server.local_bind_port) #Your TCP IP and port (your end of the tunnel)