我将MySqldb
与Python 2.7结合使用,以允许Python与其他MySQL服务器建立连接
import MySQLdb
db = MySQLdb.connect(host="sql.domain.com",
user="dev",
passwd="*******",
db="appdb")
与正常的连接不同,如何使用SSH key 对通过SSH隧道进行连接?
理想情况下,SSH隧道应该由Python打开。 SSH隧道主机和MySQL服务器是同一台计算机。
最佳答案
我猜您需要端口转发。我推荐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)
...