代码之家  ›  专栏  ›  技术社区  ›  Jim B

Python脚本中的SSH隧道卡住了

  •  6
  • Jim B  · 技术社区  · 7 年前

    我需要通过SSH进行隧道访问数据库。使用sshtunnel在Python代码中创建隧道后( https://github.com/pahaz/sshtunnel/ ),脚本挂起,不再执行其他命令。我从提供的代码中看到的最后一个打印是local\u bind\u port。之后的一切都卡住了。我是否误解了一些基本原则?

    当我通过cmd行手动创建隧道时,db连接在单独的python脚本中运行良好。

    系统:Python 3.6.1,sshtunnel 0.1.2,macOS 10.12,服务器为CentOS 7

    import pymysql.cursors
    import sshtunnel
    
    with SSHTunnelForwarder(
            ('gateway_host', gateway_port),
            ssh_username='ssh_username',
            ssh_pkey='/path/to/id_rsa',
            ssh_private_key_password='pw',
            remote_bind_address=('remote_bind', 3306),
            local_bind_address=('127.0.0.1', 3306),
            logger=create_logger(loglevel=1)
    ) as tunnel:
        print('Establishing connection')
    
        print('tunnel_bindings:', tunnel.tunnel_bindings)
        print('tunnel_is_up:', tunnel.tunnel_is_up)
        print('local_bind_port:', tunnel.local_bind_port)
    
        connection = pymysql.connect(host='127.0.0.1',
                                     port=3306,
                                     user='db_username',
                                     password='db_password',
                                     db='db_name',
                                     cursorclass=pymysql.cursors.DictCursor)
    
        try:
            with connection.cursor() as cursor:
                sql = '''SELECT VERSION();'''
                cursor.execute(sql)
                result = cursor.fetchall()
                print(result)
        finally:
            connection.close()
    
        print('Finish')
    

    日志输出(在最后一行之后卡住):

    2017-07-26 22:42:37,788| INF |  Srv-3306/1318@sshtunnel | Opening tunnel: 127.0.0.1:3306 <> remote_bind:3306
    tunnel_bindings: {('remote_bind', 3306): ('127.0.0.1', 3306)}
    tunnel_is_up: {('127.0.0.1', 3306): True}
    local_bind_port: 3306
    2017-07-26 22:42:37,864| TRA |  Thread-3/0347@sshtunnel | #1 <-- ('127.0.0.1', 63007) connected
    


    ssh -L 3306:remote_bind:3306 ssh_username@gateway_host -p gateway_port -N
    

    谢谢你的帮助

    0 回复  |  直到 7 年前