I am trying to connect my python program to a remote MySQL Database via SSH.
I am using Paramiko for SSH and SQLAlchemy.
Here is what I have so far:
import paramiko
from sqlalchemy import create_engine
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', port=port, username='user', password='pass')
engine = create_engine('mysql+mysqldb://user:pass@host/db')
I am getting an error:
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2003, "Can't connect to MySQL server on 'mcsdev.croft-it.com' (60)")
MySQL, the most popular open-source database server, listens for incoming connections only on localhost. Creating an SSH tunnel allows you to securely connect to the remote MySQL server from your local client.
To Connect to a MySQL Database Expand the Drivers node from the Database Explorer. Right-click the MySQL (Connector/J driver) and choose Connect Using.... The New Database Connection dialog box is displayed. In the Basic Setting tab, enter the Database's URL <HOST>:<PORT>/<DB> in the corresponding text field.
The ODBC driver for SQL Server implements the SSH client feature to connect to the SSH server on the remote machine at the specified port. The SSH server authenticates the client and enables the driver to establish a secure direct connection to SQL Server.
Sorry I posted a duplicated answer before. Here is a more elaborated answer tailored exactly to your question ;)
If you still in need of connecting to a remote MySQL db via SSH I have used a library named sshtunnel, that wraps ands simplifies the use of paramiko (a dependency of the sshtunnel).
With this code I think you will be good to go:
from sshtunnel import SSHTunnelForwarder
from sqlalchemy import create_engine
server = SSHTunnelForwarder(
('host', 22),
ssh_password="password",
ssh_username="username",
remote_bind_address=('127.0.0.1', 3306))
server.start()
engine = create_engine('mysql+mysqldb://user:[email protected]:%s/db' % server.local_bind_port)
# DO YOUR THINGS
server.stop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With