Enable Python to Connect to MySQL via Ssh Tunnelling

how to connect to mysql via ssh by Python

this could work:

from sshtunnel import SSHTunnelForwarder
import pymysql
import pandas as pd

server = SSHTunnelForwarder(
ssh_address=('****', 22),
ssh_username="****",
ssh_password="****",
remote_bind_address=("127.0.0.1", 3306))

server.start()

con = pymysql.connect(user='root',passwd='***',db='****',host='127.0.0.1',port=server.local_bind_port)

Query MySQL database with Python using sshtunnel, with SSH ppk key file

Use ssh_pkey parameter of SSHTunnelForwarder constructor to provide the path to your private key file.

And you will need to convert your private key file to the OpenSSH format, as Paramiko (used by sshtunnel) does not support PuTTY key format.

See How to ssh connect through python Paramiko with ppk public key

SSH Tunnel for Python MySQLdb connection

Try changing "localhost" to "127.0.0.1", it should work as you expect. This behavior is detailed in the manual:

UNIX sockets and named pipes don't
work over a network, so if you specify
a host other than localhost, TCP will
be used, and you can specify an odd
port if you need to (the default port
is 3306):

db=_mysql.connect(host="outhouse", port=3307, passwd="moonpie", db="thangs")

If you really had to, you could
connect to the local host with TCP by
specifying the full host name, or
127.0.0.1.



Related Topics



Leave a reply



Submit