pip 安装依赖报错 SSL: CERTIFICATE_VERIFY_FAILED 排障与信任源配置
执行 pip install 提示 SSLError(SSLCertVerificationError: certificate verify failed)。本文深入剖析企业安全网关解密劫持、系统根证书缺失及 trusted-host 配置实战。
在企业内部网络、使用了安全深度检测设备(如 SSL 拦截解密网关)或在刚刚安装的干净 Linux/macOS 开发环境中,执行 pip install <package> 时突然失败,终端抛出大段底层 SSL 认证异常:WARNING: Retrying ... after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)'))',随后以报错退出。
故障现象与报错信息
执行 pip 安装:
pip install requests
终端报错输出:
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:1131)'))': /simple/requests/
...
Could not fetch URL https://pypi.org/simple/requests/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131) - skipping
ERROR: No matching distribution found for requests
即使网络 ping pypi.org 完全通畅,但 pip 的 HTTPS 通道完全被证书校验拦截阻断。
根本原因剖析
- 企业内网安全设备对出网 HTTPS 流量进行动态解密劫持:
在许多大型企业或金融机构中,内网防火墙(如深信服、Zscaler、Palo Alto)会对出网流量进行动态 SSL 解密检查,并使用企业内部的私有自签名根证书重新签发替换。Python 的
certifi根证书库中并不包含该企业私有根 CA,导致握手直接被拒绝。 - 操作系统缺失系统级 CA 根证书包:在精简的 Docker 容器镜像中,缺少
ca-certificates软件包。 - macOS 原生 Python 未运行证书安装脚本:在 macOS 上通过官方 pkg 安装的 Python,默认需要用户双击运行一次
Install Certificates.command来导入钥匙串证书。
诊断排查步骤
- 验证当前 pip 使用的根证书文件路径:
python3 -c "import certifi; print(certifi.where())"
- 使用 openssl 测试 PyPI 域名的真实返回证书链:
openssl s_client -connect pypi.org:443 -servername pypi.org </dev/null
观察输出中的 Issuer(签发者)是否属于企业内部私有安全设备。
解决方案与恢复操作
方案一:通过 pip.conf 配置 trusted-host(最常用快速方案)
将目标 PyPI 源主机名标记为受信任主机,指示 pip 跳过针对该域名的 SSL 严格校验:
编辑(或新建)配置文件:
- 在 Linux / macOS:
~/.pip/pip.conf或~/.config/pip/pip.conf - 在 Windows:
%APPDATA%\pip\pip.ini
写入如下内容:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
pypi.org
files.pythonhosted.org
配置后,再次执行 pip install,依赖即可秒级完成下载,不再报证书错误。
方案二:命令行单次快捷跳过(适合临时调试)
在命令行中直接追加参数:
pip install requests --trusted-host pypi.org --trusted-host files.pythonhosted.org
方案三:为 pip 挂载企业内部自签名根证书(企业安全规范标准解法)
如果不允许使用 trusted-host,将企业的私有根证书导出,并在 pip.conf 中显式指定:
[global]
cert = /path/to/company_internal_ca.crt
pip 将直接采信该证书作为合法根证书进行验证,既保证了通信加密的安全合规,又彻底根除了验证失败。
方案四:针对 macOS 运行证书安装脚本
若在 Mac 上:
# 针对安装的具体 Python 版本运行自带的证书脚本
/Applications/Python\ 3.10/Install\ Certificates.command


