A union of curiosity and data science

Knowledgebase and brain dump of a database engineer


Connect with SSH to MySQL server with Python

from sshtunnel import SSHTunnelForwarder
import pymysql

with SSHTunnelForwarder(
('<ssh_server_ip>', 22),
ssh_username="<ssh_user>",
ssh_pkey="</location/to/your/privatekey/of/ssh/host>",
remote_bind_address=('<mysql_server_address>',<mysql_port>)
) as tunnel:
    print("SSH Connected")

    conn = pymysql.connect(
    host='127.0.0.1', user="<sql user>",
    password="<sql_user_password>", port=tunnel.local_bind_port
    )

    try:
        cur = conn.cursor()
        cur.execute('use <database>;') 
        df = pd.read_sql_query("show tables;", conn)
    finally:
        conn.close()
    
    
#di the data in the datafame. 
df.head()


 

Add comment