启用Python通过SSH隧道连接到MySQL [英] Enable Python to Connect to MySQL via SSH Tunnelling

查看:474
本文介绍了启用Python通过SSH隧道连接到MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将MySqldb与Python 2.7结合使用,以允许Python与其他MySQL服务器建立连接

I'm using MySqldb with Python 2.7 to allow Python to make connections to another MySQL server

import MySQLdb
db = MySQLdb.connect(host="sql.domain.com",
     user="dev", 
      passwd="*******", 
      db="appdb")

与其像这样正常连接,如何使用SSH密钥对通过SSH隧道进行连接?

Instead of connecting normally like this, how can the connection be made through a SSH tunnel using SSH key pairs?

理想情况下,SSH隧道应该由Python打开. SSH隧道主机和MySQL服务器是同一台机器.

The SSH tunnel should ideally be opened by Python. The SSH tunnel host and the MySQL server are the same machine.

推荐答案

我猜您需要端口转发.我建议sshtunnel.SSHTunnelForwarder

I'm guessing you'll need port forwarding. I recommend sshtunnel.SSHTunnelForwarder

import mysql.connector
import sshtunnel

with sshtunnel.SSHTunnelForwarder(
        (_host, _ssh_port),
        ssh_username=_username,
        ssh_password=_password,
        remote_bind_address=(_remote_bind_address, _remote_mysql_port),
        local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
    connection = mysql.connector.connect(
        user=_db_user,
        password=_db_password,
        host=_local_bind_address,
        database=_db_name,
        port=_local_mysql_port)
    ...

这篇关于启用Python通过SSH隧道连接到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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