Connecting to MySQL database via SSH

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

With ssh key on digital ocean

The accepted answer did not work for me, I had to specify the ssh_private_key, which is the path to your 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:[email protected]:{server.local_bind_port}'
)
dbs = engine.execute('SHOW DATABASES;')
for db in dbs:
    print(db)

server.stop()

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

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:[email protected]:%s/db' % server.local_bind_port)

# DO YOUR THINGS

server.stop()