Python - SSH Tunnel Setup and MySQL DB Access

拥有回忆 提交于 2019-11-26 23:38:19

问题


I am trying to connect to my server from my local(windows) and access the MySQL DB

With the below code setting up the SSH tunnel through putty, I am not able to access the MySQL DB.

con = None
con = mdb.connect(user='user',passwd='password',db='database',host='127.0.0.1',port=3308)
cur = con.cursor()

With the below code, I am using paramiko to setup SSH tunnel which is successful but I am not able to connect to MySQL DB

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', username='username', password='password')

con = None
con = mdb.connect(user='user',passwd='password',db='database',host='127.0.0.1',port=3308)
cur = con.cursor()

Error:
Error 2003: Can't connect to MySQL server on '127.0.0.1' (10061)

Do I have change the MySQL connecting string settings to access MySQL DB using paramiko If not I need to add anymore parameter for paramiko to simulate SSH tunnel setup like putty.


回答1:


You can use sshtunnel wrapper for paramiko and save you headaches ;)

from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
         ('host', 22),
         ssh_password="password",
         ssh_username="username",
         remote_bind_address=('127.0.0.1', 3308)) as server:

    con = None
    con = mdb.connect(user='user',passwd='password',db='database',host='127.0.0.1',port=server.local_bind_port)
    cur = con.cursor()


来源:https://stackoverflow.com/questions/12989866/python-ssh-tunnel-setup-and-mysql-db-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!