Connect MySQL with ssh tunnel in Python

Sometimes you can only connect to MySQL via a certain server for security reasons. But apparently, coding in IDE(e.g PyCharm) is easier. For this circumstance, we can use sshtunnel.

So we have a MySQL server on, its mysql login name and password is MYSQL_USER and MYSQL_PASSWORD. And we can only connect to this mysql via server, and its login name and password is root and SERVER_PASSWORD. Let’s figure out how sshtunnel is working.

with SSHTunnelForwarder(('', 22), ssh_password='SERVER_PASSWORD', ssh_username='root', remote_bind_address=('', 3306)) as server:
conn = MySQLdb.connect(host='', port=server.local_bind_port, user='MYSQL_USER', passwd='MYSQL_PASSWORD')
cursor = conn.cursor()