ssh first with mysqldb in python

前端 未结 2 1758
孤独总比滥情好
孤独总比滥情好 2020-12-16 06:52

I\'m trying to connect to a MySQL database on a remote server using MySQLdb in python. The problem is that first I need to SSH into the host, and then from there, I need to

2条回答
  •  盖世英雄少女心
    2020-12-16 07:17

    I prefer keeping the tunnel within the python code, I did hate to create tunnels manually, or separately, thanks to sshtunnel library its very simple to use.

    Here is some simple sample that will work for what you want.

    import MySQLdb
    from sshtunnel import SSHTunnelForwarder
    
    with SSHTunnelForwarder(
             ('sshhost.domain.com', 22),
             ssh_password="sshpasswd",
             ssh_username="sshusername",
             remote_bind_address=('mysqlhost.domain.com', 3306)) as server:
    
        conn = MySQLdb.connect(host='127.0.0.1',
                               port=server.local_bind_port,
                               user='user',
                               passwd='password',
                               db='dbname')
    

提交回复
热议问题