通过SSH连接MySQL数据库

时间:2015-05-12 10:56:39

标签: python sqlalchemy paramiko

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

3 个答案:

答案 0 :(得分:11)

抱歉,我之前发过了重复的答案。以下是针对您的问题量身定制的更详细的答案;)

如果您仍然需要通过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()

答案 1 :(得分:1)

此代码对我有用

        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)

答案 2 :(得分:0)

使用外部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()