通过 SSH 连接到 MySQL 数据库 [英] Connecting to MySQL database via SSH
问题描述
我正在尝试通过 SSH 将我的 python 程序连接到远程 MySQL 数据库.
I am trying to connect my python program to a remote MySQL Database via SSH.
我将 Paramiko 用于 SSH 和 SQLAlchemy.
I am using Paramiko for SSH and SQLAlchemy.
这是我目前所拥有的:
import paramiko
from sqlalchemy import create_engine
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', port=port, username='user', password='pass')
engine = create_engine('mysql+mysqldb://user:pass@host/db')
我收到一个错误:
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2003, "Can't connect to MySQL server on 'mcsdev.croft-it.com' (60)")
推荐答案
抱歉,我之前发布了重复的答案.这是针对您的问题量身定制的更详细的答案;)
Sorry I posted a duplicated answer before. Here is a more elaborated answer tailored exactly to your question ;)
如果您仍然需要通过 SSH 连接到远程 MySQL 数据库,我使用了一个名为 sshtunnel 的库,它封装了 paramiko(sshtunnel 的一个依赖项).
If you still in need of connecting to a remote MySQL db via SSH I have used a library named sshtunnel, that wraps ands simplifies the use of paramiko (a dependency of the sshtunnel).
有了这个代码,我认为你会很高兴:
With this code I think you will be good to go:
from sshtunnel import SSHTunnelForwarder
from sqlalchemy import create_engine
server = SSHTunnelForwarder(
('host', 22),
ssh_password="password",
ssh_username="username",
remote_bind_address=('127.0.0.1', 3306))
server.start()
engine = create_engine('mysql+mysqldb://user:pass@127.0.0.1:%s/db' % server.local_bind_port)
# DO YOUR THINGS
server.stop()
这篇关于通过 SSH 连接到 MySQL 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!