简体   繁体   English

通过 SSH 连接到 MySQL 数据库

[英]Connecting to MySQL database via SSH

I am trying to connect my python program to a remote MySQL Database via SSH.我正在尝试通过 SSH 将我的 python 程序连接到远程 MySQL 数据库。

I am using Paramiko for SSH and SQLAlchemy.我将 Paramiko 用于 SSH 和 SQLAlchemy。

Here is what I have so far:这是我到目前为止所拥有的:

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

I am getting an error:我收到一个错误:

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 ;)这是针对您的问题量身定制的更详细的答案;)

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).如果您仍然需要通过 SSH 连接到远程 MySQL 数据库,我使用了一个名为 sshtunnel 的库,它封装了 ands 简化了 paramiko(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()

This code work for me这段代码对我有用

        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)

Using external ubuntu server使用外部ubuntu server

With ssh key on digital ocean在数字海洋上使用ssh key

The accepted answer did not work for me, I had to specify the ssh_private_key , which is the path to your private 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM