【问题标题】:python mysql connectivity via sshpython mysql 通过 ssh 连接
【发布时间】:2015-10-08 12:46:31
【问题描述】:

我使用以下步骤手动连接到我的数据库:

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 

现在我可以成功查询任何内容,例如 select * from my_table。

我有一个 python selenium webdriver 代码,我想从中读取我的数据库。由于 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()

我收到此错误:

BaseSSHTunnelForwarderError: 无法解析 %s 的 IP 地址,正在中止!

【问题讨论】:

    标签: python mysql selenium ssh


    【解决方案1】:

    实例化SSHTunnelForwarder时:

    参数host 是你的远程ssh 2.2.2.2
    remote_bind_address 的参数将用于隧道,端口是您要隧道的端口,因此是您的 mysql 端口。 ('3.3.3.3', 3306)

    然后,当连接到 mysql 时,您希望它通过隧道访问 mysql 实例。隧道端口是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)
    

    【讨论】:

    • 2015-10-08 19:59:26,322 |警告 |无法读取 SSH 配置文件:~/.ssh/config 2015-10-08 19:59:26,375 |信息 |连接到网关:2.2.2.2:1111 作为用户“login1”。 2015-10-08 19:59:47,375 |错误 |无法连接到网关:2.2.2.2 Traceback(最近一次调用最后一次):文件“D:\API.py”,第 23 行,在 remote_bind_address=('3.3.3.3', 3306)) 作为服务器:文件“C:\Python27\lib\site-packages\sshtunnel.py”,第 626 行,在 init 中引发 BaseSSHTunnelForwarderError(msg) BaseSSHTunnelForwarderError:无法连接到网关:2.2.2.2
    • Could not read SSH configuration file: ~/.ssh/config。可能是权限问题。
    • 这是否意味着我的主机文件中应该有一个 ip?
    • 可悲的是sshtunel 忽略了原始错误。你能把C:\Python27\lib\site-packages\sshtunnel.py中的this line转换成except paramiko.SSHException as err: msg = 'Could not connect to gateway: {0}\n{1}'.format(ssh_host, err)
    • 无法连接到2.2.2.2:[Errno 10060]连接尝试失败,因为连接方在一段时间后没有正确响应或建立连接失败,因为连接的主机没有响应跨度>
    猜你喜欢
    • 2014-02-18
    • 2020-10-10
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2014-03-21
    相关资源
    最近更新 更多