通过 SSH 连接到 MySQL 数据库

Connecting to MySQL database via SSH

我正在尝试通过 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()

这段代码对我有用

        import pymysql
        import paramiko
        from paramiko import SSHClient
        from sshtunnel import SSHTunnelForwarder
        from sqlalchemy import create_engine

        #ssh config
        mypkey = paramiko.RSAKey.from_private_key_file('your/user/location/.ssh/id_rsa')             
        ssh_host = 'your_ssh_host'
        ssh_user = 'ssh_host_username'
        ssh_port = 22  

        #mysql config         
        sql_hostname = 'your_mysql_host name'
        sql_username = 'mysql_user'
        sql_password = 'mysql_password'
        sql_main_database = 'your_database_name'
        sql_port = 3306
        host = '127.0.0.1'



        with SSHTunnelForwarder(
                (ssh_host, ssh_port),
                ssh_username=ssh_user,
                ssh_pkey=mypkey,
                remote_bind_address=(sql_hostname, sql_port)) as tunnel:              

            engine = create_engine('mysql+pymysql://'+sql_username+':'+sql_password+'@'+host+':'+str(tunnel.local_bind_port)+'/'+sql_main_database)
            connection = engine.connect()
            print('engine creating...')
            sql = text(""" select * from nurse_profiles np limit 50""")
            nurseData = connection.execute(sql)
            connection.close()


            nurseList = []
            for row in nurseData:
                nurseList.append(dict(row))
            print('nurseList len: ', len(nurseList))
            print('nurseList: ', nurseList)

使用外部 ubuntu server

在数字海洋ssh key

已接受的答案对我不起作用,我必须指定 ssh_private_key,这是您私钥的路径

from sqlalchemy import create_engine
from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
     ('133.22.166.19', 22),
     ssh_password="123ABC123",
     ssh_username="erfan",
     ssh_private_key=r'C:\Users\Erfan\.ssh\id_rsa',
     remote_bind_address=('127.0.0.1', 3306)
)

server.start()

engine = create_engine(
    f'mysql+mysqldb://root:safepassword123@127.0.0.1:{server.local_bind_port}'
)
dbs = engine.execute('SHOW DATABASES;')
for db in dbs:
    print(db)

server.stop()