我需要通过SSH隧道才能访问数据库。使用sshtunnel(https://github.com/pahaz/sshtunnel/)在Python代码中创建隧道后,脚本挂起,不再执行其他命令。我从提供的代码中看到的最后一个打印是local_bind_port。之后的一切都被卡住了。我误解了一些基本原则吗?
当我通过cmd行手动创建隧道时,db连接在单独的python脚本中正常工作。
系统:Python 3.6.1,sshtunnel 0.1.2,macOS 10.12,服务器是CentOS 7
Python代码:
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隧道:
ssh -L 3306:remote_bind:3306 ssh_username@gateway_host -p gateway_port -N
感谢您的帮助