You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python通过SSH隧道连接AWS RDS失败求助:隧道已建立但连接卡住

SSH隧道连接AWS RDS卡住问题求助

使用以下代码通过SSH隧道连接AWS RDS数据库,隧道已成功建立,但后续连接环节卡住。当前使用的PEM文件在DBeaver中可正常使用,相关代码及隧道信息如下:

代码示例

with SSHTunnelForwarder(
        ('15.164.xxx.xxx',22),  # SSH host and port
        ssh_username='ec2-user',  # SSH user_name
        ssh_pkey='key-stg-evchg-xxxxxxxxxx.pem',
        remote_bind_address=('rds-stg-evchg-cluster.cluster-xxxxxxxxxxxxxx.ap-northeast-2.rds.amazonaws.com', 3306)) as tunnel:
    print(tunnel)

    conn = pymysql.connect(
        host="127.0.0.1",
        port=tunnel.local_bind_port,
        user="user",
        password="password"
    )

隧道信息

<class 'sshtunnel.SSHTunnelForwarder'> object
ssh gateway: 15.164.xxx.xxx:22
proxy: no
username: ec2-user
authentication: {'pkeys': [('ssh-rsa', b'7295dd6621412412312312fedf')]}
hostkey: not checked
status: started
keepalive messages: every 5.0 sec
tunnel connection check: disabled
concurrent connections: allowed
compression: not requested
logging level: ERROR
local binds: [('0.0.0.0', 0)]
remote binds: [('rds-stg-evchg-cluster.cluster-cvrtu5pd6rrl.xxxxxxxxxx.amazonaws.com', 3306)]

排查建议

  • 检查RDS安全组:确认EC2实例所在的安全组被允许访问RDS的3306端口(RDS入站规则需包含EC2的安全组或IP)
  • 补充数据库名称:在pymysql.connect中添加db="你的目标数据库名",部分场景下未指定数据库会导致连接停滞
  • 开启调试日志:将SSHTunnelForwarder的logging_level设为logging.DEBUG,查看连接过程中的详细错误输出
  • 测试本地连接:隧道建立后,用MySQL命令行工具连接127.0.0.1:{tunnel.local_bind_port},验证端口转发是否正常,排除pymysql库的问题
  • 验证EC2到RDS的连通性:登录EC2实例,执行telnet rds-stg-evchg-cluster.cluster-xxxxxxxxxxxxxx.ap-northeast-2.rds.amazonaws.com 3306,确认EC2能直接访问RDS端口

内容的提问来源于stack exchange,提问作者ChangSun An

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:25:22