Connecting to MySQL database via SSH

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

    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:safepassword123@127.0.0.1:{server.local_bind_port}'
    )
    dbs = engine.execute('SHOW DATABASES;')
    for db in dbs:
        print(db)
    
    server.stop()
    

提交回复
热议问题