简体   繁体   English

通过ssh的python mysql连接

[英]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. 现在,我可以成功查询任何内容,例如从my_table中选择*。

I have a python selenium webdriver code from where I want to read my db. 我有一个python selenium webdriver代码,我想从这里读取数据库。 I am not able to achieve it because of ssh tunnelling and 3 IP's involved. 由于ssh隧道传输和涉及3个IP,我无法实现它。

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! BaseSSHTunnelForwarderError:无法为%s解析IP地址,正在中止!

When instantiating SSHTunnelForwarder : 实例化SSHTunnelForwarder

The param host is your remote ssh 2.2.2.2 . 参数host是您的远程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. remote_bind_address参数将用于隧道,该端口是您要隧道的端口,因此是您的mysql端口。 ('3.3.3.3', 3306)

Then when connecting to mysql, you want it to pass though the tunnel to access the mysql instance. 然后,当连接到mysql时,您希望它通过隧道访问mysql实例。 The tunnel port is server.local_bind_port . 隧道端口是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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