Connecting to MySQL database via SSH

后端 未结 3 636
我在风中等你
我在风中等你 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 09:03

    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:pass@127.0.0.1:%s/db' % server.local_bind_port)
    
    # DO YOUR THINGS
    
    server.stop()
    

提交回复
热议问题