Python Requests客户端证书配置引发ConnectionError求助
Python Requests配置客户端证书时触发PermissionError问题
问题背景
将Postman中可正常运行的请求迁移至Python Requests,初始使用Postman生成的代码片段可正常运行,但厂商要求添加客户端证书验证(Postman中已通过Settings > Certificates分别为Staging环境.staging.example.com、Sandbox环境.sandbox.example.com配置证书),修改代码后无论传入pem+key元组还是单独文件,均触发权限错误。
Postman生成的初始代码
import requests url = "example.com/request" payload='auth_type=client_credentials' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic auth_token' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text)
修改后的代码(添加证书配置)
import requests url = "example.com/request" payload='auth_type=client_credentials' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic auth_token' } S = requests.Session() cert = ("/path/to/.pem", "/path/to/.key") response = requests.request("POST", url, headers=headers, data=payload, cert=cert, verify=False, allow_redirects=True) print(response.text)
触发的错误信息
Exception has occurred: ConnectionError
('Connection aborted.', PermissionError(1, 'Operation not permitted'))
解决办法
1. 修复证书文件权限
类Unix系统下,确保运行Python的用户拥有证书文件的读取权限,执行命令:
chmod 600 /path/to/.pem /path/to/.key
Windows系统右键证书文件→属性→安全→为当前运行Python的用户添加读取权限。
2. 修正代码中的问题
- 补全URL协议头:
url必须包含http://或https://,否则requests无法识别请求类型。 - 实际使用Session实例:代码中创建了Session但未使用,改用Session管理证书和连接更可靠:
import requests # 补全协议头 url = "https://example.com/request" payload='auth_type=client_credentials' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic auth_token' } cert = ("/path/to/.pem", "/path/to/.key") # 使用Session发送请求 s = requests.Session() s.cert = cert # 仅测试环境使用verify=False,生产环境请设置为CA证书路径 response = s.post(url, headers=headers, data=payload, verify=False, allow_redirects=True) print(response.text)
3. 检查证书格式
- 确认
.pem文件包含完整的证书链,格式正确。 - 如果私钥
.key设置了密码,需要在cert参数中添加密码:cert = ("/path/to/.pem", "/path/to/.key", "your_private_key_password")
4. 确认路径正确性
确保证书文件的路径是绝对路径,或者相对于Python脚本运行目录的正确相对路径,避免因路径错误导致无法读取文件。
内容的提问来源于stack exchange,提问作者FreakShow
相关产品推荐
相关产品推荐

