In Python applications, accessing MySQL databases is often necessary. To establish secure connections, one technique involves using an SSH tunnel. This article explores how to leverage SSH key pairs to create an SSH tunnel and facilitate MySQL connectivity through Python.
Consider the following Python code:
import MySQLdb db = MySQLdb.connect(host="sql.domain.com", user="dev", passwd="*******", db="appdb")
While the above code establishes a direct connection to the MySQL server, there may be scenarios where an SSH tunnel is required for enhanced security. An SSH tunnel encrypts the connection, providing a secure channel for communication.
To set up an SSH tunnel and connect to MySQL using Python, follow these steps:
Here's an example code snippet that demonstrates these steps:
import pymysql import paramiko import pandas as pd from paramiko import SSHClient from sshtunnel import SSHTunnelForwarder from os.path import expanduser # SSH Parameters home = expanduser('~') mypkey = paramiko.RSAKey.from_private_key_file(home + pkeyfilepath) ssh_host = 'ssh_hostname' ssh_user = 'ssh_username' ssh_port = 22 # MySQL Parameters sql_hostname = 'sql_hostname' sql_username = 'sql_username' sql_password = 'sql_password' sql_main_database = 'db_name' sql_port = 3306 with SSHTunnelForwarder( (ssh_host, ssh_port), ssh_username=ssh_user, ssh_pkey=mypkey, remote_bind_address=(sql_hostname, sql_port)) as tunnel: conn = pymysql.connect(host='127.0.0.1', user=sql_username, passwd=sql_password, db=sql_main_database, port=tunnel.local_bind_port) # Perform database operations here... conn.close()
By implementing these techniques, you can securely connect to a MySQL server via an SSH tunnel in Python. This approach ensures data confidentiality and integrity, making it suitable for applications that require elevated security measures.
The above is the detailed content of How to Securely Connect to MySQL via SSH Tunneling in Python?. For more information, please follow other related articles on the PHP Chinese website!