mysql.connector通过SSH隧道连接RDS MySQL失败,pymysql可正常连接
问题描述
SSH隧道已成功建立,但通过隧道连接RDS MySQL时抛出错误:2003 (HY000): Can't connect to MySQL server on '0.0.0.0:52678' (10049)。使用pymysql库能正常连接,但用mysql.connector就失败,相关代码如下:
# Create an SSH tunnel to the RDS instance via the bastion host with sshtunnel.SSHTunnelForwarder( ssh_config['ssh_host'], ssh_username=ssh_config['ssh_username'], ssh_private_key=ssh_config['ssh_private_key'], remote_bind_address=(rds_config['host'], rds_config['port']) ) as tunnel: print("SSH tunnel created successfully") # Connect to the RDS instance through the SSH tunnel conn = mysql.connector.connect( user=rds_config['user'], password=rds_config['password'], host=tunnel.local_bind_host, port=tunnel.local_bind_port, database=rds_config['database'] )
排查与解决思路
强制指定本地连接地址为127.0.0.1
sshtunnel默认的local_bind_host是0.0.0.0,部分环境下mysql.connector对这个地址的解析有兼容性问题,直接把连接的host改成127.0.0.1即可,端口仍使用tunnel.local_bind_port。升级mysql.connector到最新版
旧版本的mysql.connector在处理动态端口或0.0.0.0绑定的socket时存在bug,执行以下命令升级:pip install --upgrade mysql-connector-python显式设置隧道的本地绑定地址
创建SSHTunnelForwarder时手动指定local_bind_address参数,强制绑定到127.0.0.1,避免地址解析问题:with sshtunnel.SSHTunnelForwarder( ssh_config['ssh_host'], ssh_username=ssh_config['ssh_username'], ssh_private_key=ssh_config['ssh_private_key'], remote_bind_address=(rds_config['host'], rds_config['port']), local_bind_address=('127.0.0.1', 0) # 0表示自动分配可用端口 ) as tunnel:检查本地端口监听状态
用命令确认隧道的本地端口是否正常监听:- Windows:
netstat -ano | findstr 52678 - Linux/macOS:
lsof -i :52678
如果发现端口只绑定在0.0.0.0,就直接用127.0.0.1连接,不要用tunnel.local_bind_host返回的地址。
- Windows:
内容的提问来源于stack exchange,提问作者Lavish Karankar
相关产品推荐
相关产品推荐

