本地运行Google认证脚本出现SSLError问题求助
解决本地Ubuntu虚拟机访问Google服务时的SSLError(X509 PEM lib)
问题背景
本地Ubuntu虚拟机运行脚本时触发以下SSLError,生产环境可正常运行,已排除服务账号问题:
google.auth.exceptions.TransportError: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by SSLError(SSLError(524297, '[X509] PEM lib (_ssl.c:4149)')))
解决方案
1. 重置系统SSL根证书
Ubuntu系统的根证书异常是常见诱因,执行以下命令重新安装并更新证书:
sudo apt update && sudo apt install --reinstall ca-certificates sudo update-ca-certificates -f
2. 强制Python使用系统SSL证书
部分Python环境(如虚拟环境)可能未正确关联系统证书,可通过以下方式修复:
- 先查看当前Python的SSL证书配置:
import ssl print(ssl.get_default_verify_paths()) - 若输出的证书路径为空或错误,设置环境变量(临时生效):
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs - 或在脚本开头添加强制配置:
import os os.environ['SSL_CERT_FILE'] = '/etc/ssl/certs/ca-certificates.crt' os.environ['SSL_CERT_DIR'] = '/etc/ssl/certs'
3. 排查代理与防火墙干扰
- 若本地启用了代理,先关闭代理测试:
unset http_proxy https_proxy - 检查UFW防火墙是否限制HTTPS出站:
sudo ufw status - 若存在限制,允许HTTPS流量:
sudo ufw allow out 443/tcp
4. 更新加密相关依赖库
旧版本的加密库可能存在兼容性问题,执行升级:
pip install --upgrade google-auth gspread requests cryptography
5. 确认服务账号文件的权限与路径
- 确保凭证文件权限正确,避免读取失败:
chmod 600 backend/credentials.json - 使用绝对路径加载凭证文件,避免相对路径错误:
修改google_authentication函数:import os def google_authentication(credentials) -> object: scope = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'] # 使用绝对路径 abs_credentials = os.path.abspath(credentials) creds = Credentials.from_service_account_file( abs_credentials, scopes=scope) client = gspread.authorize(creds) return client
内容的提问来源于stack exchange,提问作者Marco Rodrigues
相关产品推荐
相关产品推荐

