gpt4 book ai didi

python - 通过SSH连接到MySQL数据库

转载 作者:行者123 更新时间:2023-12-03 16:44:24 26 4
gpt4 key购买 nike

我正在尝试通过SSH将python程序连接到远程MySQL数据库。

我正在将Paramiko用于SSH和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)")

最佳答案

抱歉,我之前发布了重复的答案。这是为您的问题量身定制的更详尽的答案;)

如果仍然需要通过SSH连接到远程MySQL数据库,我使用了一个名为sshtunnel的库,该库可以包装和简化paramiko(sshtunnel的依赖项)的使用。

有了这段代码,我认为您会很高兴:

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

关于python - 通过SSH连接到MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30188796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com