Connecting to MySQL database via SSH

后端 未结 3 639
我在风中等你
我在风中等你 2021-02-06 08:37

I am trying to connect my python program to a remote MySQL Database via SSH.

I am using Paramiko for SSH and SQLAlchemy.

Here is what I have so far:

<         


        
3条回答
  •  抹茶落季
    2021-02-06 08:59

    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)
    

提交回复
热议问题