Python SSLError: CERTIFICATE_VERIFY_FAILED 完整修复指南(macOS / Linux / Windows)
一、这个错误到底在报什么
在 Python 里看到 SSLError 并且消息里带 CERTIFICATE_VERIFY_FAILED,含义只有一个:TLS 握手时客户端拿到了服务器证书,但用自己信任库里的根证书验证不了这条证书链。它不是网络不通,也不是服务器挂了,几乎都是「本机信任库不全或过期」,或者「服务器用的是自签、企业内网证书,客户端不认识」。
最常见的完整堆栈长这样:
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=443):
Max retries exceeded with url: /v1/users
(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]
certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))
真正有用的是冒号后面那句原因,较新版本的 Python 基本都会带上:
unable to get local issuer certificate:信任库里没有签发这张证书的根 CA,或者服务器没下发中间证书。self-signed certificate/self-signed certificate in certificate chain:证书链里出现了自签证书。certificate has expired/certificate is not yet valid:证书过期,或者本机时间不对。Hostname mismatch, certificate is not valid for 'xxx':域名或 IP 与证书 SAN 不匹配。unable to verify the first certificate:只拿到叶子证书,中间证书缺失。
还有一个关键前提:不同库用的信任库根本不是同一个。
requests、httpx、urllib3 2.x:默认使用 certifi 自带的cacert.pem。urllib.request、http.client、aiohttp:默认走ssl.create_default_context(),也就是 OpenSSL 的系统默认路径(Linux 上通常是/etc/ssl/certs)。- macOS 上 python.org 官方安装包:certifi 不会自动接入,必须跑一次
Install Certificates.command。
所以「curl 能通、Python 不通」是这类问题最典型的症状——curl 用的是系统信任库,requests 用的是 certifi。
二、三分钟定位:先分清是哪一类问题
不要急着改代码,按下面四步走,能覆盖 90% 的场景。
第一步:确认解释器与信任库版本。
python -V
python -c 'import ssl; print(ssl.OPENSSL_VERSION); print(ssl.get_default_verify_paths())'
python -m certifi
pip show certifi | head -n 3
python -m certifi 会直接打印当前环境使用的 cacert.pem 路径。注意虚拟环境:每个 venv 有自己的一份 certifi,升级 A 环境不会影响 B 环境。
第二步:用 openssl 直接看服务器返回的证书链和校验结果。
openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts </dev/null
重点看结尾的 Verify return code:
Verify return code: 0 (ok)
Verify return code: 20 (unable to get local issuer certificate)
Verify return code: 10 (certificate has expired)
如果这里就是 20,说明服务器下发的链不完整或者你缺根 CA,跟 Python 代码没关系。
第三步:用 curl 做对照实验。
curl -vI https://api.example.com
curl 通、Python 不通 → 信任库差异;两者都不通 → 服务器证书链或本机时间有问题。
第四步:确认报错来自哪个库。看堆栈最内层,requests、urllib3、aiohttp、botocore 的处理方式各不相同,见第四、第五节。
三、方案 A:修好 certifi 和系统根证书
macOS(python.org 官方安装包,最常见)
这是原文提到的场景,也是最容易踩的坑:从 python.org 下载的安装包自带一个独立的 Python 框架,certifi 的 CA 文件默认不会被识别,必须执行官方附带的脚本。
pip install --upgrade certifi
ls -d /Applications/Python 3.*
bash '/Applications/Python 3.12/Install Certificates.command'
脚本做的事很简单:在 Python 框架目录下创建指向 certifi 的 cacert.pem 符号链接。所以升级到新的 Python 版本(比如 3.12 → 3.13)后,必须对新目录重跑一次。
Homebrew 安装的 Python 不需要这个脚本,它链接的是 Homebrew 的 openssl,必要时执行 brew install ca-certificates 即可。
Linux
sudo apt-get update && sudo apt-get install -y ca-certificates
sudo update-ca-certificates
sudo dnf install -y ca-certificates
sudo update-ca-trust extract
Windows
python -m pip install --upgrade certifi
certutil -addstore -f Root corp-root-ca.crt
Windows 上 OpenSSL 的默认路径经常不存在,所以 urllib 直接报错而 requests 正常,是很常见的现象。
容器镜像
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
alpine 用 apk add --no-cache ca-certificates。slim 和 alpine 默认都不带根证书,这是 CI 里报这个错的头号原因。
conda 环境
conda install -c conda-forge certifi ca-certificates
conda config --set ssl_verify /etc/ssl/certs/corp-ca.pem
四、方案 B:在代码和配置里显式指定 CA
当只有部分服务需要企业 CA 时,改代码比改全局信任库更安全,影响面也更小。
requests
import requests
r = requests.get('https://api.example.com/v1/users', verify='/etc/ssl/certs/corp-ca.pem', timeout=10)
print(r.status_code)
import requests
session = requests.Session()
session.verify = '/etc/ssl/certs/corp-ca-bundle.pem'
session.headers.update({'User-Agent': 'my-service/1.0'})
httpx
import httpx
with httpx.Client(verify='/etc/ssl/certs/corp-ca.pem', timeout=10) as client:
print(client.get('https://api.example.com/v1/users').status_code)
aiohttp
import asyncio, ssl, aiohttp
async def main():
ctx = ssl.create_default_context(cafile='/etc/ssl/certs/corp-ca.pem')
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=ctx)) as sess:
async with sess.get('https://api.example.com/v1/users') as resp:
print(await resp.text())
asyncio.run(main())
urllib3 与 urllib.request
import urllib3
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs='/etc/ssl/certs/corp-ca.pem')
print(http.request('GET', 'https://api.example.com/v1/users').status)
import ssl, urllib.request
ctx = ssl.create_default_context(cafile='/etc/ssl/certs/corp-ca.pem')
with urllib.request.urlopen('https://api.example.com/v1/users', context=ctx, timeout=10) as resp:
print(resp.status)
boto3
import boto3
s3 = boto3.client('s3', verify='/etc/ssl/certs/corp-ca.pem')
环境变量:不改代码的写法
export REQUESTS_CA_BUNDLE=/etc/ssl/certs/corp-ca-bundle.pem
export CURL_CA_BUNDLE=/etc/ssl/certs/corp-ca-bundle.pem
export SSL_CERT_FILE=/etc/ssl/certs/corp-ca-bundle.pem
export AWS_CA_BUNDLE=/etc/ssl/certs/corp-ca-bundle.pem
注意生效范围不同:REQUESTS_CA_BUNDLE 只对 requests 生效;SSL_CERT_FILE 影响 OpenSSL 默认上下文,也就是 urllib、http.client、aiohttp 这一类;AWS_CA_BUNDLE 给 botocore。requests 和 httpx 不读 SSL_CERT_FILE,这是很多人「设了没用」的原因。
pip 与 git
pip config set global.cert /etc/ssl/certs/corp-ca-bundle.pem
pip install --cert /etc/ssl/certs/corp-ca-bundle.pem requests
git config --global http.sslCAInfo /etc/ssl/certs/corp-ca-bundle.pem
直接复用操作系统信任库
pip install truststore pip-system-certs
import truststore
truststore.inject_into_ssl()
import requests
print(requests.get('https://api.example.com/health').status_code)
truststore 让 Python 直接使用 macOS Keychain、Windows 证书存储或 Linux 系统信任库,对企业环境和被 MDM 管理的机器特别省事,要求 Python 3.10 及以上。
五、方案 C:企业内网、自签证书与 HTTPS 代理
公司用 Zscaler、Netskope 这类 HTTPS 中间人代理时,服务器证书是由企业根 CA 现场签发的。根 CA 装在系统里,curl 就通了,但 certifi 不认识,Python 于是报 unable to get local issuer certificate。
导出服务器证书链
openssl s_client -showcerts -connect internal.example.com:443 -servername internal.example.com chain.txt
awk '/BEGIN CERTIFICATE/,/END CERTIFICATE/' chain.txt > internal-chain.pem
与企业根 CA 合并成一个 bundle
cat "$(python -m certifi)" /etc/ssl/certs/corp-root-ca.pem > /etc/ssl/certs/corp-ca-bundle.pem
合并后既能访问公网站点,也能访问内网服务。缺点是 certifi 升级后需要重新合并一次,建议写进镜像构建脚本或配置管理里,而不是手工维护。
自签证书的正确用法
生成时务必写 SAN,CN 在现代客户端里已经不作为主机名校验依据了:
openssl req -x509 -newkey rsa:4096 -sha256 -days 825 -nodes -keyout key.pem -out cert.pem -subj '/CN=internal.example.com' -addext 'subjectAltName=DNS:internal.example.com,DNS:*.internal.example.com,IP:10.0.0.5'
然后在客户端显式信任它,而不是关掉校验:
import requests
r = requests.get('https://internal.example.com/api', verify='/etc/ssl/certs/internal-chain.pem', timeout=10)
双向 TLS(mTLS)
import requests
r = requests.get(
'https://internal.example.com/api',
cert=('/etc/ssl/client.crt', '/etc/ssl/client.key'),
verify='/etc/ssl/certs/corp-ca.pem',
timeout=10,
)
六、方案对比:选哪个、有什么代价
| 方案 | 典型命令 / 代码 | 适用场景 | 风险与注意 |
|---|---|---|---|
| 升级 certifi | pip install -U certifi |
公网证书校验失败、certifi 过旧 | 每个 venv 独立,需逐个升级 |
| Install Certificates.command | bash '/Applications/Python 3.12/Install Certificates.command' |
macOS python.org 安装包 | 升级 Python 后要重跑,仅影响该版本 |
| 系统信任库 | sudo update-ca-certificates |
服务器、容器、系统级 Python | 需要 root,影响整机所有程序 |
| 环境变量 | export REQUESTS_CA_BUNDLE=... |
CI、临时调试、容器 | 各库读取的变量不同;路径写错会静默回退 |
| 代码内 verify | requests.get(url, verify=...) |
单个服务需要企业 CA | 路径硬编码,部署时容易漏文件 |
| 合并 bundle | cat "$(python -m certifi)" ca.pem > bundle.pem |
同时访问公网与内网 | certifi 升级后要重新合并 |
| truststore | truststore.inject_into_ssl() |
想直接复用操作系统信任库 | 需 Python 3.10+,少数库不兼容 |
| verify=False | requests.get(url, verify=False) |
仅限本地抓包 | 关闭证书链与主机名校验,可被中间人解密,禁止进生产 |
七、排错手册:真实错误信息逐条拆解
1. unable to get local issuer certificate
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)
信任库里找不到签发者。按顺序排查:
openssl s_client -showcerts输出里只有一张证书 → 服务器没下发中间证书,让运维补全链。- 输出里有多张,但根 CA 是企业自签 → 把企业根 CA 加进 certifi 或指定
verify。 - 什么都不缺但还是报错 →
SSL_CERT_FILE指向了不存在的文件,OpenSSL 会静默使用空信任库。
2. self-signed certificate in certificate chain
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1006)
公司代理或内网服务用了自签证书。用 verify=/path/ca.pem 显式信任,而不是关掉校验。
3. certificate has expired
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1006)
先确认服务器证书有效期:
openssl s_client -connect api.example.com:443 -servername api.example.com /dev/null | openssl x509 -noout -dates
如果 notAfter 还没到却报过期,检查本机时间:容器、树莓派、长期休眠的笔记本时间漂移非常常见,date -u 一看便知。
4. Hostname mismatch
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'api.example.com'. (_ssl.c:1006)
证书 SAN 里没有你请求的域名。常见于用 IP 访问、用内部别名访问,或者证书只签了裸域没签 *.example.com。解决办法是让服务端补 SAN,或者客户端改用它签过的域名。
5. 老版本 Python 没有原因说明
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:997)
冒号后面没内容,说明 Python 或 OpenSSL 版本较老。别猜,直接用 openssl s_client 拿 Verify return code,或者升级 Python 获得更明确的报错。
6. pip 装包时报同样的错
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)'))': /simple/requests/
pip 有自己的证书配置,REQUESTS_CA_BUNDLE 对它无效:
pip config set global.cert /etc/ssl/certs/corp-ca-bundle.pem
pip config list
7. 打包成 exe 后才报错
PyInstaller、cx_Freeze 打包后 certifi 的 cacert.pem 没被收集进去,开发环境正常、发布版报错。解决办法:
pyinstaller --collect-data certifi app.py
8. 只有某些库报错,其他正常
说明它们的信任库不同。requests 正常、urllib 报错,就是 certifi 与 OpenSSL 系统路径的差异;反过来则是系统信任库缺根 CA。按第四节的变量表逐一对齐即可。
八、验证与调试工具箱
改完之后不要靠猜,用下面这段脚本确认握手和证书链是否真的通过:
python - <<'PY'
import socket, ssl
host = 'api.example.com'
ctx = ssl.create_default_context()
with socket.create_connection((host, 443), timeout=10) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as s:
print('TLS:', s.version(), s.cipher()[0])
cert = s.getpeercert()
print('subject:', dict(x[0] for x in cert['subject']))
print('issuer :', dict(x[0] for x in cert['issuer']))
print('notAfter:', cert['notAfter'])
print('SAN:', cert.get('subjectAltName'))
PY
能打印出 issuer 和 SAN,说明校验通过;如果抛 SSLCertVerificationError,把 create_default_context() 换成 create_default_context(cafile='/path/ca.pem') 再试,就能确定是不是 CA 配置的问题。
另外两个命令值得常备:
python -c 'import ssl; print(ssl.get_default_verify_paths())'
python -c 'import certifi; print(certifi.where())'
前者告诉你 OpenSSL 会去哪里找证书,后者告诉你 requests 会去哪里找证书——两个路径不一致,就是大部分「明明装了证书还是报错」的根源。
九、FAQ
为什么 curl 能访问,Python 却报 CERTIFICATE_VERIFY_FAILED?
因为用的不是同一份信任库。curl 走操作系统信任库(macOS 是 Keychain,Linux 是 /etc/ssl/certs),requests 和 httpx 走 certifi 自带的 cacert.pem。企业根 CA 装进系统后 curl 立刻可用,Python 仍需单独处理。
生产代码能不能用 verify=False?
不能。verify=False 同时关闭证书链校验和主机名校验,TLS 退化成「加密但不认证」,中间人可以正常解密和篡改流量。只在本地抓包时临时打开,并确保这个开关不可能被带到生产配置里。
已经 pip install –upgrade certifi 了,为什么还报错?
三个高频原因:一是在 A 虚拟环境升级、报错的是 B 环境;二是代码里显式传了 verify= 路径,环境变量和 certifi 都被覆盖;三是缺的是中间证书,服务器下发的链本身就不完整,客户端再怎么装根 CA 也没用。
macOS 上每次升级 Python 都要重跑 Install Certificates.command 吗?
要。脚本只对具体的 Python 版本框架目录生效,新装 3.13 之后不会继承 3.12 的链接。
certifi 和系统证书到底该用哪个?
面向公网的服务用 certifi,更新快、跨平台一致、不依赖系统状态;内网服务、装了 HTTPS 代理的机器、被 MDM 管理的终端,用系统信任库或合并 bundle 更省事。
怎么让 Python 直接使用操作系统信任库?
pip install truststore,在程序入口调用 truststore.inject_into_ssl()。pip 自身可以装 pip-system-certs。需要 Python 3.10 及以上。
Docker 镜像里为什么也报这个错?
python:slim 和 alpine 基础镜像默认不安装 ca-certificates。在 Dockerfile 里加一行 apt-get install -y ca-certificates(alpine 用 apk add ca-certificates)即可。
自签证书怎么做到既安全又不用 verify=False?
把自签 CA 或自签证书本身通过 verify='/path/ca.pem' 显式信任,并确保证书 SAN 里包含实际访问的域名或 IP。这样校验依然完整,只是把信任范围收窄到你自己的 CA。
设置了 SSL_CERT_FILE 却没生效?
requests 和 httpx 不读这个变量,要用 REQUESTS_CA_BUNDLE。另外变量值必须是真实存在的 PEM 文件,指向不存在的路径时 OpenSSL 会静默回退到空信任库,报错信息反而更让人迷惑。
报错里的 (_ssl.c:1006) 是什么?
CPython 源码行号,只说明异常由 ssl 模块抛出,不同 Python 版本数字不同,对定位没有帮助。真正要看的是冒号后面的原因描述。