Python通过SSH隧道连接Aurora DB失败:无法建立SSH网关会话
解决Python通过SSH隧道连接Aurora时的"Could not establish session to SSH gateway"错误
以下是针对终端SSH正常但Python代码连接失败的排查和解决步骤:
1. 确认密钥文件的路径与权限
- 终端能识别相对路径的密钥,但Python运行环境可能无法定位,替换为密钥文件的绝对路径,比如
/home/your-user/key.pem - 密钥文件权限必须严格设为
600,执行命令:
Python对文件权限的要求比终端更严格,权限过宽会导致密钥验证失败chmod 600 /path/to/key.pem
2. 手动加载SSH密钥(避免自动识别错误)
sshtunnel自动识别密钥类型可能出现异常,用paramiko显式加载密钥:
import paramiko from sshtunnel import SSHTunnelForwarder import pymysql try: # 显式加载RSA密钥 private_key = paramiko.RSAKey.from_private_key_file('/绝对路径/key.pem') with SSHTunnelForwarder( ('10.100.100.10', 22), ssh_username="ec2-user", ssh_pkey=private_key, remote_bind_address=('prd-example-aurora.cluster-ro-example.ap-northeast-2.rds.amazonaws.com', 3306) ) as tunnel: print("== SSH Tunnel ==") # 后续数据库连接代码保持不变 db = pymysql.connect( host='127.0.0.1', user="example", password="example", port=tunnel.local_bind_port ) try: with db.cursor() as cur: cur.execute('SHOW DATABASES') for r in cur: print(r) finally: db.close() print("SSH success !!") except Exception as e: print("Error:", str(e))
3. 开启调试日志定位具体错误
添加日志配置,查看SSH连接过程中的详细报错信息:
import logging # 开启DEBUG级别日志 logging.basicConfig(level=logging.DEBUG) from sshtunnel import SSHTunnelForwarder import pymysql # 后续代码不变
日志会输出密钥验证、握手过程的细节,帮助定位是超时、密钥不匹配还是其他问题
4. 修复sshtunnel与paramiko版本兼容性
部分版本组合存在兼容性问题,尝试安装稳定兼容版本:
pip uninstall -y sshtunnel paramiko pip install sshtunnel==0.4.0 paramiko==2.12.0
5. 禁用HostKey检查(匹配终端SSH行为)
终端SSH可能配置了跳过HostKey检查,但Python代码默认启用,添加参数关闭:
with SSHTunnelForwarder( ('10.100.100.10', 22), ssh_username="ec2-user", ssh_pkey="/绝对路径/key.pem", remote_bind_address=('prd-example-aurora.cluster-ro-example.ap-northeast-2.rds.amazonaws.com', 3306), # 禁用HostKey检查 ssh_options={"StrictHostKeyChecking": "no"} ) as tunnel: # 后续代码不变
6. 手动指定本地绑定端口
如果随机端口被占用,显式指定本地端口:
with SSHTunnelForwarder( ('10.100.100.10', 22), ssh_username="ec2-user", ssh_pkey="/绝对路径/key.pem", remote_bind_address=('prd-example-aurora.cluster-ro-example.ap-northeast-2.rds.amazonaws.com', 3306), # 指定本地端口 local_bind_address=('127.0.0.1', 3307) ) as tunnel: # 数据库连接端口改为3307 db = pymysql.connect( host='127.0.0.1', user="example", password="example", port=3307 ) # 后续代码不变
内容的提问来源于stack exchange,提问作者Tera Ha
相关产品推荐
相关产品推荐

