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

PyMongo连接MongoDB Atlas报[SSL: CERTIFICATE_VERIFY_FAILED]错误求助

解决PyMongo连接MongoDB Atlas时的SSL证书过期错误

问题分析

错误提示certificate has expired,说明本地系统根证书库未包含MongoDB Atlas当前有效的SSL证书,或依赖的加密库版本过旧,无法完成证书验证。

解决方案

1. 更新系统根证书

系统根证书过期会导致无法识别Atlas的SSL证书,根据操作系统执行对应操作:

  • Windows:打开「设置」→「更新和安全」→「Windows更新」,安装所有可用更新(包含根证书更新)。
  • macOS:打开「系统设置」→「通用」→「软件更新」,安装最新系统更新。
  • Ubuntu/Debian:执行命令:
    sudo apt update && sudo apt install --reinstall ca-certificates
    
  • CentOS/RHEL:执行命令:
    sudo yum update ca-certificates
    

2. 更新PyMongo及加密依赖库

旧版本的PyMongo或cryptography库可能无法正确处理新SSL证书,执行升级命令:

pip install --upgrade pymongo cryptography

3. 强制指定TLS版本

确保连接使用TLS 1.2及以上版本,修改代码如下:

from pymongo.mongo_client import MongoClient
import ssl

uri = "mongodb+srv://<USER NAME>:<USER PASS>@<URL I GOT FROM ATLAS>/?retryWrites=true&w=majority"

# 指定TLS 1.2版本
client = MongoClient(uri, tls=True, tlsAllowInvalidCertificates=False, tlsVersion=ssl.TLSVersion.TLS_1_2)

print('created mongo client')

try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

4. 临时绕过证书验证(仅测试环境使用)

注意:此方法会降低安全性,禁止在生产环境使用,修改代码添加参数:

client = MongoClient(uri, tlsAllowInvalidCertificates=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:05:34