Python SSLError: CERTIFICATE_VERIFY_FAILED 完全解决指南(macOS、requests、自签证书与企业内网 CA)
一、报错长什么样:先认清 traceback
这个错误在不同的 HTTP 客户端里有不同的外壳,但内核都是同一句 [SSL: CERTIFICATE_VERIFY_FAILED]。先看几个真实形态,确认自己遇到的是哪一种:
Traceback (most recent call last):
File 'app.py', line 12, in <module>
r = requests.get('https://api.example.com/v1/ping', timeout=10)
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /v1/ping
(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))
标准库 urllib 的版本:
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)>
aiohttp 的版本:
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host api.example.com:443 ssl:True
[SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]
根本原因只有一句话:Python 用本地信任库去校验服务器返回的证书链,无法把它补全到任何受信任的根证书,于是主动中断握手。触发场景归纳为三类:
- 本地根本没有可用 CA 包:macOS 上从 python.org 下载的安装包不会自动执行证书安装脚本;Docker 的 slim / alpine 基础镜像默认不带
ca-certificates。 - 证书不是公共 CA 签发的:自签证书、企业内网 CA、公司出口代理做 TLS 中间人(MITM)解密。
- 服务器证书链本身不完整或已失效:只下发叶子证书没下发中间证书、证书过期、SAN 字段不包含你访问的域名。
还要警惕环境变量:SSL_CERT_FILE、REQUESTS_CA_BUNDLE、CURL_CA_BUNDLE、PIP_CERT 会被子进程继承。CI/CD 里经常有人把它们指向一个已删除的路径,结果出现「本地能跑、流水线报错」或反向的诡异现象。
二、三步定位:是缺 CA,还是证书本身有问题
第 1 步:读细分文案
CERTIFICATE_VERIFY_FAILED 后面的半句才是关键,它直接决定处理方向:
unable to get local issuer certificate:本地信任库缺根证书或中间证书。self-signed certificate in certificate chain:链里出现了自签证书,通常是企业代理或内部服务。certificate has expired/certificate is not yet valid:服务器证书过期,或本机系统时间跑偏。Hostname mismatch, certificate is not valid for 'x.x.x.x':用 IP 访问了只签了域名的证书。
第 2 步:确认 Python 实际在用哪个 CA 文件
import ssl, certifi
print(ssl.OPENSSL_VERSION)
print(ssl.get_default_verify_paths())
print(certifi.where())
重点看 certifi.where() 指向的文件是否存在、是否可读。虚拟环境里 certifi 可能来自另一个 site-packages,多环境并存时尤其容易错位。
第 3 步:用 openssl / curl 交叉验证服务器证书链
echo | openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null | openssl x509 -noout -subject -issuer -dates
curl -v https://api.example.com/v1/ping -o /dev/null
判断规则很清晰:curl 也失败说明是服务端证书链或本机系统信任库的问题;curl 成功而 Python 失败说明是 Python 侧的 CA 配置问题(大概率是 certifi 过期或没装)。
三、方案一:安装或升级 certifi,补齐系统 CA
这是最常见也最容易被忽略的一步。certifi 是一个随包发布的 CA 根证书集合,公共 CA 轮换后老版本的 certifi 会失效。
python -m pip install --upgrade certifi
python -c 'import certifi; print(certifi.where())'
macOS:python.org 安装包必须手动跑一次脚本
从 python.org 下载的 pkg 安装器不带证书,需要执行安装目录里的 Install Certificates.command:
ls -d /Applications/Python 3.*/
/Applications/Python 3.12/Install Certificates.command
或者直接用 Finder 双击该文件。这一步的本质是把 certifi 的 cacert.pem 链接进 Python 的 OpenSSL 默认搜索路径。Homebrew 安装的 Python 走另一套逻辑:
brew install ca-certificates
export SSL_CERT_FILE=$(brew --prefix)/etc/ca-certificates/cert.pem
Linux / 容器
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y ca-certificates && sudo update-ca-certificates
# Alpine
apk add --no-cache ca-certificates
# RHEL / CentOS
sudo yum install -y ca-certificates
Dockerfile 里请显式加上这一层,不要指望基础镜像自带:
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
&& rm -rf /var/lib/apt/lists/*
RUN python -m pip install --upgrade certifi
四、方案二:在代码里显式指定 CA 包
当服务端用的是自签证书或企业内网 CA 时,最干净的做法是把企业根证书合并进一个 bundle,然后在客户端显式指定,而不是去动全局信任库。
requests
import certifi, requests
# 公共站点:显式使用 certifi,避免被环境里残留的 REQUESTS_CA_BUNDLE 影响
r = requests.get('https://api.example.com/v1/ping', verify=certifi.where(), timeout=10)
# 内网服务:指向企业 bundle
r = requests.get('https://intranet.corp/api', verify='/etc/ssl/certs/company-bundle.pem', timeout=10)
# 整个会话复用
s = requests.Session()
s.verify = '/etc/ssl/certs/company-bundle.pem'
urllib3
import certifi, urllib3
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
resp = http.request('GET', 'https://api.example.com/v1/ping')
httpx
import httpx
with httpx.Client(verify='/etc/ssl/certs/company-bundle.pem', timeout=10) as client:
print(client.get('https://api.example.com/v1/ping').status_code)
aiohttp
import aiohttp, certifi, ssl
ctx = ssl.create_default_context(cafile=certifi.where())
async def main():
connector = aiohttp.TCPConnector(ssl=ctx)
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get('https://api.example.com/v1/ping') as resp:
print(resp.status)
标准库 urllib
import certifi, ssl, urllib.request
ctx = ssl.create_default_context(cafile=certifi.where())
with urllib.request.urlopen('https://api.example.com/v1/ping', context=ctx, timeout=10) as resp:
print(resp.status)
pip 与命令行工具
python -m pip install --upgrade pip --cert /etc/ssl/certs/company-bundle.pem
# 或者用环境变量,让 pip / requests / curl 一起生效
export PIP_CERT=/etc/ssl/certs/company-bundle.pem
export REQUESTS_CA_BUNDLE=/etc/ssl/certs/company-bundle.pem
export SSL_CERT_FILE=/etc/ssl/certs/company-bundle.pem
export CURL_CA_BUNDLE=/etc/ssl/certs/company-bundle.pem
一个高频误区:requests 默认使用 certifi 的 bundle,不读系统信任库,所以只设置 SSL_CERT_FILE 对 requests 是无效的,必须设置 REQUESTS_CA_BUNDLE 或代码里传 verify=。
五、方案三:自签证书与企业内网 CA 的正确姿势
生产环境的正确做法永远是「让客户端信任该 CA」,而不是「关掉校验」。流程如下:
# 1. 拿到企业根证书并核对指纹(找运维要,别从报错里猜)
openssl x509 -in company-root.crt -noout -subject -fingerprint -sha256
# 2. 把企业根证书与公共 CA bundle 合并
python -c 'import certifi; print(certifi.where())'
cat company-root.crt /usr/local/lib/python3.12/site-packages/certifi/cacert.pem > company-bundle.pem
# 3. 验证合并结果
openssl verify -CAfile company-bundle.pem server-chain.pem
本地开发需要自签证书时,务必把 SAN 写全,否则一定撞上 Hostname mismatch:
openssl req -x509 -newkey rsa:2048 -nodes
-keyout key.pem -out cert.pem -days 365
-subj '/CN=localhost'
-addext 'subjectAltName=DNS:localhost,DNS:api.local,IP:127.0.0.1'
服务端只下发叶子证书会导致部分客户端校验失败,用下面这条命令确认是否返回了中间证书:
echo | openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts 2>/dev/null | grep -c 'BEGIN CERTIFICATE'
结果大于 1 才说明链完整。Nginx 里应把 ssl_certificate 配置成「叶子证书 + 中间证书」拼接后的文件。
六、各客户端 CA 配置方式对比
| 客户端 / 库 | 默认信任库来源 | 指定 CA 的方式 | 相关环境变量 |
|---|---|---|---|
| requests | certifi 的 cacert.pem(不读系统库) | verify='/path/bundle.pem'、Session.verify |
REQUESTS_CA_BUNDLE、CURL_CA_BUNDLE |
| urllib3 v2 | certifi | PoolManager(ca_certs=...) |
SSL_CERT_FILE(部分版本) |
| httpx | certifi | Client(verify=...) |
SSL_CERT_FILE |
| aiohttp | ssl.create_default_context()(系统库) |
TCPConnector(ssl=ctx) |
SSL_CERT_FILE、SSL_CERT_DIR |
| urllib / http.client | ssl.create_default_context()(系统库) |
urlopen(..., context=ctx) |
SSL_CERT_FILE |
| pip | 内置 vendored certifi | --cert /path/bundle.pem |
PIP_CERT |
| curl | 系统信任库 | --cacert /path/bundle.pem |
CURL_CA_BUNDLE |
| boto3 / botocore | certifi | verify= 参数 |
AWS_CA_BUNDLE |
从表中可以看出最容易踩坑的两点:requests 系列不读系统信任库;aiohttp 和 urllib 读系统信任库。同一个进程里两种库混用,就会出现「一个接口通、另一个接口报错」的现象。
七、排查手册:真实报错对照表
1. unable to get local issuer certificate (_ssl.c:1006)
最典型的一条。Python 3.10+ 行号为 1006,Python 3.9 及更早是 1129,含义完全相同。
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)
处理:先 pip install --upgrade certifi;macOS 再执行 Install Certificates.command;内网服务则显式传 verify=/path/company-bundle.pem。如果 curl 也报同样错误,说明是服务端没下发中间证书,找运维补链。
2. self-signed certificate in certificate chain (_ssl.c:1007)
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1007)
原因:公司网络出口有 TLS 解密代理,它用自己的根证书重新签发了站点证书。升级 certifi 永远解决不了。处理:向 IT 索取代理根证书,合并进 bundle 后设置 REQUESTS_CA_BUNDLE。
3. certificate has expired
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1006)
处理:先排查本机时间:date -u,容器里时钟漂移非常常见。时间正常则是服务端证书真过期了,用第二节的 openssl 命令看 notAfter 确认。
4. Hostname mismatch
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for '10.20.30.40'. (_ssl.c:1006)
原因:用 IP 直接访问,而证书 SAN 里只有域名。处理:改用域名访问;或重新签发证书,在 SAN 中加入 IP:10.20.30.40。不要靠关校验绕过。
5. pip 安装时失败
Could not fetch URL https://pypi.org/simple/requests/: There was a problem confirming the ssl certificate:
HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/requests/
(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))
处理:python -m pip install --upgrade pip --cert /path/company-bundle.pem,或设置 PIP_CERT。不要长期使用 --trusted-host pypi.org,那等于把依赖供应链暴露给中间人。
6. 看似证书问题、实则不是
[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1006)
原因:用 https:// 访问了 HTTP 端口(或反向代理配置错)。处理:检查 URL scheme 与端口,这类错误升级证书没有任何作用。
7. 虚拟环境里改不动
python -c 'import certifi; print(certifi.__file__)'
如果打印出的路径不在你当前激活的 venv 下,说明 PYTHONPATH 或系统级 site-packages 抢先了。用 python -m pip install --upgrade --force-reinstall certifi 在当前解释器里重装。
八、生产红线:为什么不要用 verify=False
网上大量答案的终点是这一行,但它只是把安全机制拆掉:
requests.get(url, verify=False) # 反面教材
httpx.get(url, verify=False) # 反面教材
aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) # 反面教材
关闭校验后,任何能控制网络路径的人(公共 Wi-Fi、被污染的 DNS、恶意代理)都可以用自签证书冒充目标站点,你的 Bearer Token、Cookie、请求体全部明文暴露,而代码层面不会有任何提示。requests 只会打印一条 InsecureRequestWarning,很多人顺手就 urllib3.disable_warnings() 把它也关掉了。
替代方案按推荐度排序:
- 把企业根 CA 合并进 bundle 并随应用分发(首选,见第五节)。
- 证书指纹固定(pinning):校验服务端证书的 SHA-256 指纹,适合无法拿到 CA 的极端场景。
- 只在本地调试临时关闭,且必须用环境变量控制而不是写死在代码里:
if os.getenv('ALLOW_INSECURE') == '1': verify = False。
建议在 CI 里加一条静态检查,防止有人把关闭校验的代码合进主干:
grep -rn --include='*.py' -E 'verifys*=s*False|CERT_NONE|ssls*=s*False' . && exit 1 || exit 0
九、FAQ
问:为什么浏览器和 curl 都能访问,只有 Python 报错?
答:因为它们用的是不同的信任库。浏览器和 curl 用操作系统信任库(macOS 是 Keychain,Linux 是 /etc/ssl/certs),而 requests / httpx / urllib3 默认用 certifi 自带的 cacert.pem。企业根证书装进了系统钥匙串,Python 却看不到,于是报错。解决办法是显式指定 verify= 或设置 REQUESTS_CA_BUNDLE。
问:升级 certifi 之后还是报同样的错?
答:按顺序检查三件事:certifi.where() 打印的路径是否是你刚升级的那个环境;环境变量 REQUESTS_CA_BUNDLE 是否指向了一个旧的、已删除的文件(它的优先级高于 certifi);报错细分文案是否是 self-signed certificate in certificate chain(这类问题升级 certifi 无效)。
问:Docker 镜像里怎么彻底解决?
答:在 Dockerfile 里 apt-get install -y ca-certificates 之后执行 update-ca-certificates,并 pip install --upgrade certifi。内网构建还需要 COPY company-root.crt /usr/local/share/ca-certificates/ 再 update-ca-certificates。不要把证书文件挂载进容器后忘了更新信任库。
问:证书链不完整为什么只有部分客户端报错?
答:有些客户端会自行用 AIA(Authority Information Access)扩展去下载缺失的中间证书,有些不会。Python 的 OpenSSL 默认不会。所以同一台服务器在浏览器里正常、在 Python 里报 unable to get local issuer certificate。修复点在服务端:把中间证书拼进 ssl_certificate 文件。
问:公司代理环境下所有 HTTPS 请求都失败怎么办?
答:先确认代理地址:echo $HTTPS_PROXY。然后向 IT 索取代理的根证书,合并进 bundle,并同时设置 HTTPS_PROXY 与 REQUESTS_CA_BUNDLE。注意 requests 会自动读取 HTTPS_PROXY,但不会自动信任代理的证书,这两件事必须分别处理。
问:能不能直接用系统的 CA 目录,不用 certifi?
答:可以。Python 3.10+ 支持 SSL_CERT_DIR,或者构造上下文时传 capath:ssl.create_default_context(capath='/etc/ssl/certs')。好处是与系统包管理器同步更新;坏处是可移植性差,同一份代码在 macOS 和 Alpine 上路径不同。跨平台项目建议以 certifi 为基线、企业证书按需合并。
问:报错里说证书 not yet valid 是什么情况?
答:本机时间比服务器证书的生效时间还早,几乎都是容器或虚拟机时钟漂移导致。执行 date -u 与 ntpdate -q pool.ntp.org 校准,证书本身通常没问题。