pip3 install sshtunnel
通过ssh跳板机B连接目标主机A
import pymysql from sshtunnel import SSHTunnelForwarder server = SSHTunnelForwarder( ssh_address_or_host='39.100.88.221', # 跳板机B地址 ssh_port=22, # 跳板机B端口 ssh_username='', # 跳板机B账号 ssh_password='fdfdafdffffff', # 跳板机B密码 # local_bind_address=('127.0.0.1', 22), # 这里必须填127.0.0.1 remote_bind_address=('rm-vy1c36g83gfff2u6m.mysql.rds.aliyuncs.com', 3306) # 目标机器A地址,端口 ) server.start() conn = pymysql.connect( host='127.0.0.1', # 这里必须填127.0.0.1 port=server.local_bind_port , # 本地映射端口 user='business', # 目标机器A账号 password='fdfdsfweweqf', # 目标机器A密码 db='business_db' # 目标机器A要连的库 ) cursor = conn.cursor() cursor.execute('select count(*) from cangku') ret = cursor.fetchall() print(ret) conn.close() server.stop() # 这里要填stop print('stop')
补充:
存在local_bind_address=('127.0.0.1', 22),这行代码的时候,有的环境会出现如下问题
MySQLdb._exceptions.OperationalError: (2013, "Lost connection to server at 'handshake: reading initial communication packet', system error: 0")