通过SSH隧道连接Amazon DocumentDB遇证书验证失败问题求助
解决SSH隧道连接Amazon DocumentDB的证书验证问题
问题场景
我有一个位于私有VPC中的Amazon DocumentDB集群,只能通过SSH堡垒机访问。通过SSH隧道将数据库服务转发到本地后,使用pymongo连接时出现以下错误:
ServerSelectionTimeoutError: 0.0.0.0:53374: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '0.0.0.0'. (_ssl.c:997), Timeout: 30s, Topology Description: ]>
错误原因
Amazon DocumentDB的SSL证书是绑定其集群域名的,但SSH隧道默认将服务转发到本地0.0.0.0,pymongo验证证书时发现域名/IP不匹配,导致验证失败。
解决方法(推荐生产环境使用)
1. 修改本地hosts文件
将DocumentDB集群域名映射到127.0.0.1,让本地访问该域名时指向隧道的本地端口:
- Linux/macOS:编辑
/etc/hosts,添加一行:127.0.0.1 your-documentdb-cluster-name.region.docdb.amazonaws.com - Windows:编辑
C:\Windows\System32\drivers\etc\hosts,添加上述内容(需管理员权限)
2. 调整SSH隧道与连接代码
修改代码,保持DocumentDB域名作为连接地址,仅替换端口为隧道的本地绑定端口,同时指定正确的SSL参数:
from sshtunnel import SSHTunnelForwarder import pymongo, json def format_db_uri(user,password,host,port,**kwargs): h1 = f'mongodb://{user}:{password}@{host}:{port}/?' options = '&'.join(f'{k}={v}' for k,v in kwargs.items()) print(options) return h1 + options def connect_mongo_via_bastion(config): ssh_config = dict(config['bastion']) mongo_config = dict(config['mongo']) # 指定本地绑定地址为127.0.0.1,自动分配可用端口 server = SSHTunnelForwarder( **ssh_config, remote_bind_address=(mongo_config['host'], mongo_config['port']), local_bind_address=('127.0.0.1', 0) ) server.start() # 仅替换连接端口,保留DocumentDB原域名 mongo_config['port'] = server.local_bind_address[1] # 强制启用SSL,并配置AWS CA证书路径 mongo_config.update({ 'ssl': 'true', 'ssl_ca_certs': '/本地路径/rds-combined-ca-bundle.pem' }) client = pymongo.MongoClient(format_db_uri(**mongo_config)) return client, server
3. 下载AWS CA证书
获取AWS官方提供的适用于DocumentDB的CA证书文件(如rds-combined-ca-bundle.pem),保存到本地后,将代码中的ssl_ca_certs路径替换为实际文件路径。
临时测试方案(不推荐生产环境)
如果仅用于测试,可以关闭SSL主机名验证(存在安全风险),在mongo_config中添加:
mongo_config.update({ 'ssl': 'true', 'tlsAllowInvalidHostnames': 'true' })
此方法跳过证书的主机名匹配检查,仅适合临时调试使用。
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

