Python-SSH隧道设置和MySQL数据库访问 [英] Python - SSH Tunnel Setup and MySQL DB Access

查看:100
本文介绍了Python-SSH隧道设置和MySQL数据库访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从本地Windows连接到服务器并访问MySQL数据库

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

使用以下代码通过腻子设置SSH隧道时,我无法访问 MySQL数据库.

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()

使用以下代码,我正在使用paramiko设置SSH隧道,该隧道成功了,但是我无法连接到MySQL DB

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)

我是否更改了MySQL连接字符串设置以使用paramiko访问MySQL DB?如果没有,我需要为paramiko添加更多参数以模拟SSH隧道设置(如腻子).

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.

推荐答案

您可以将sshtunnel包装器用于paramiko并节省您的头痛;)

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()

这篇关于Python-SSH隧道设置和MySQL数据库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆