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

Python连接MongoDB Atlas遇SSL证书验证失败,求解决方法

解决MongoDB Atlas连接时的SSL证书验证失败问题

第一步:修复连接字符串格式错误

你的连接字符串存在格式问题,用户名与密码的分隔逻辑和包裹格式不正确。正确格式应为:

mongodb+srv://<用户名>:<密码>@test.umh3xqu.mongodb.net/?retryWrites=true&w=majority

你当前的字符串中,<My-Username:<My-Password> 部分缺少闭合符号且分隔错误,需修正为 <My-Username>:<My-Password>。

第二步:解决SSL证书验证问题

修复连接字符串后若仍出现证书错误,可按以下方案处理:

方案1:更新系统根证书(推荐)

  • Windows:通过系统更新安装最新根证书,或手动导入可信根证书。
  • macOS:运行Python安装目录下的 Install Certificates.command 脚本(路径通常为 /Library/Frameworks/Python.framework/Versions/[你的Python版本]/bin/),更新本地证书存储。
  • Linux:更新系统CA证书包,例如Debian/Ubuntu执行:
    sudo apt-get update && sudo apt-get install ca-certificates
    
    RHEL/CentOS执行:
    sudo yum update ca-certificates
    

方案2:指定CA证书文件

从MongoDB Atlas控制台获取官方CA证书文件,连接时通过 tlsCAFile 参数指定证书路径:

import pymongo
from pymongo.server_api import ServerApi

client = pymongo.MongoClient(
    "mongodb+srv://<你的用户名>:<你的密码>@test.umh3xqu.mongodb.net/?retryWrites=true&w=majority",
    server_api=ServerApi('1'),
    tlsCAFile="/path/to/your/ca-certificate.crt"
)

print(client.list_database_names())

方案3:临时禁用证书验证(仅应急,禁止生产环境使用)

添加 tlsAllowInvalidCertificates=True 参数跳过证书验证,此方法会降低连接安全性,仅用于临时测试:

import pymongo
from pymongo.server_api import ServerApi

client = pymongo.MongoClient(
    "mongodb+srv://<你的用户名>:<你的密码>@test.umh3xqu.mongodb.net/?retryWrites=true&w=majority",
    server_api=ServerApi('1'),
    tlsAllowInvalidCertificates=True
)

print(client.list_database_names())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:01:05