简体   繁体   中英

python mysql connectivity via ssh

I connect to my db manually using these steps:

1>load a putty session with ip 1.1.1.1 and port 1111  
2>login as: login1  
3>login1@1.1.1.1's password: pwd1  
4>[login1@G ~]$ ssh login1@2.2.2.2  
5>[login1@l ~]$ MySQL -h 3.3.3.3 -u login2 -p'pwd2' -D mydb 

Now I can can query anything successfully like select * from my_table.

I have a python selenium webdriver code from where I want to read my db. I am not able to achieve it because of ssh tunnelling and 3 IP's involved.

from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
         ('host', 1111),
         ssh_password="pwd1
         ssh_username="login1",
         remote_bind_address=('2.2.2.2', 1111)) as server:

    con = None
    con = MySQLdb.connect(user='login2',passwd='pwd2',db='mydb',host=3.3.3.3,port=3306)
    cur = con.cursor()

I am getting this error:

BaseSSHTunnelForwarderError: Could not resolve IP address for %s, aborting!

When instantiating SSHTunnelForwarder :

The param host is your remote ssh 2.2.2.2 .
Argument for remote_bind_address will be for the tunnel, the port is the one you want to tunnel, so your mysql port. ('3.3.3.3', 3306)

Then when connecting to mysql, you want it to pass though the tunnel to access the mysql instance. The tunnel port is server.local_bind_port .

from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
    ('2.2.2.2', 1111),
    ssh_password="pwd1"
    ssh_username="login1",
    remote_bind_address=('3.3.3.3', 3306)) as server:

    con = MySQLdb.connect(
        user='login2',passwd='pwd2',
        db='mydb',host=1.1.1.1,
        port=server.local_bind_port)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM