为所有环境下的Python Requests添加SSL证书的自动化方案
解决公司SSL检查下Python Requests的证书配置问题
1. 现有conda环境自动化配置证书
写批量脚本遍历所有conda环境,自动追加根证书:
- 先把从Chrome导出的根证书保存为
company_root_cert.pem,放在机器本地或共享路径 - Linux/macOS执行脚本:
# 遍历所有conda环境路径 for env_path in $(conda info --envs | grep -v "^#" | awk '{print $2}'); do # 定位certifi的cacert.pem文件 cacert_path=$(find "$env_path/lib" -name "cacert.pem" | grep certifi) if [ -n "$cacert_path" ]; then # 追加根证书 cat /path/to/company_root_cert.pem >> "$cacert_path" echo "已更新环境: $env_path" fi done
- Windows PowerShell脚本:
$certPath = "C:\path\to\company_root_cert.pem" # 获取所有conda环境路径 $envs = conda info --envs | Select-String -Pattern "^[^#]" | ForEach-Object { $_.Line.Split()[1] } foreach ($env in $envs) { $cacertPath = Get-ChildItem -Path "$env\Lib" -Name "cacert.pem" -Recurse | Where-Object { $_.FullName -match "certifi" } if ($cacertPath) { Get-Content $certPath | Add-Content $cacertPath.FullName Write-Host "已更新环境: $env" } }
2. 新创建conda环境自动配置证书
推荐两种实用方案:
方案一:用环境变量绕开certifi修改
设置REQUESTS_CA_BUNDLE环境变量,Requests会优先使用该路径的证书,无需改动certifi文件:
- 全局生效:修改conda全局配置文件
.condarc,添加:
env_vars: REQUESTS_CA_BUNDLE: "/path/to/company_root_cert.pem"
- 单个环境生效:创建环境后,在环境的
etc/conda/activate.d目录添加脚本:
Linux/macOS创建set_cert_env.sh:export REQUESTS_CA_BUNDLE="/path/to/company_root_cert.pem"
Windows创建set_cert_env.bat:set REQUESTS_CA_BUNDLE=C:\path\to\company_root_cert.pem
方案二:conda创建后自动追加证书
在conda钩子目录(Linux/macOS为~/.conda/hooks,Windows为C:\Users\<用户名>\.conda\hooks)创建post_create.sh(或post_create.bat),脚本内容参考现有环境的自动化逻辑,只处理当前新创建的环境路径。
3. certifi更新后覆盖手动修改内容的处理
方案一:锁定certifi版本
在环境的environment.yml中指定固定版本,防止自动更新:
dependencies: - certifi=2024.2.2 # 替换为当前使用的版本号
或用命令锁定:
conda install certifi=2024.2.2 --freeze-installed
方案二:使用环境变量(推荐)
直接用REQUESTS_CA_BUNDLE指向自定义证书文件,完全脱离certifi的cacert.pem依赖,更新certifi不会影响证书配置,这是最可持续的方案。
方案三:自动恢复证书
在conda钩子目录创建post_update.sh(Linux/macOS),当certifi更新后自动重新追加根证书:
if echo "$CONDA_PACKAGES" | grep -q "certifi"; then cacert_path=$(find "$CONDA_PREFIX/lib" -name "cacert.pem" | grep certifi) if [ -n "$cacert_path" ]; then cat /path/to/company_root_cert.pem >> "$cacert_path" echo "已恢复公司根证书到certifi" fi fi
内容的提问来源于stack exchange,提问作者beginner_
相关产品推荐
相关产品推荐

