Enable Python to connect to MySQL through SSH tunneling

I am using MySqldb with Python 2.7 to allow Python to make connections to another MySQL server

 import MySQLdb db = MySQLdb.connect(host="sql.domain.com", user="dev", passwd="*******", db="appdb") 

Instead of connecting normally, how can I do this, can I connect through the SSH tunnel using SSH key pairs?

Ideally, the SSH tunnel should be open to Python. The SSH tunnel host and MySQL server are the same machine.

+8
python mysql ssh
source share
2 answers

I assume that you will need port forwarding. I recommend sshtunnel.SSHTunnelForwarder

 import mysql.connector import sshtunnel with sshtunnel.SSHTunnelForwarder( (_host, _ssh_port), ssh_username=_username, ssh_password=_password, remote_bind_address=(_remote_bind_address, _remote_mysql_port), local_bind_address=(_local_bind_address, _local_mysql_port) ) as tunnel: connection = mysql.connector.connect( user=_db_user, password=_db_password, host=_local_bind_address, database=_db_name, port=_local_mysql_port) ... 
+7
source share

Paramiko is the best python module for ssh tunneling. Check out the code here: https://github.com/paramiko/paramiko/blob/master/demos/forward.py

As stated in the comments, this works just fine. SSH tunnel for connecting to Python MySQLdb

+1
source share

All Articles