Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to MySQL database via SSH

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)")
like image 587
Mantis Avatar asked May 12 '15 10:05

Mantis


People also ask

Does MySQL use SSH?

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.

How do I connect to a MySQL database?

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.

Can you SSH into SQL Server?

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.


1 Answers

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()
like image 179
jsjc Avatar answered Sep 28 '22 22:09

jsjc