Windows 10下Python实现cURL双向SSL认证的可行方案求助
解决Python Requests双向SSL认证连接重置问题
先给出对应curl命令的正确Requests实现代码:
import requests url = "https://sample.com/api/Accounts" headers = { "Content-Type": "application/json", "Authorization": "Bearer <Token>" } data = {} # 配置双向SSL认证参数 verify = "CA.pem" # 指定CA根证书文件 cert = ("server.crt", "server.key") # 传入客户端证书和私钥对 try: response = requests.post(url, headers=headers, json=data, verify=verify, cert=cert) response.raise_for_status() # 主动抛出HTTP错误状态码 print(response.json()) except requests.exceptions.RequestException as e: print(f"请求失败: {e}")
针对你遇到的ConnectionResetError(10054)错误,可从以下几个方向排查解决:
- 证书路径验证:Windows环境下Python的工作目录可能和Git Bash不一致,建议直接使用证书的绝对路径(比如
C:/certs/CA.pem),避免相对路径解析错误。 - 证书格式检查:Requests依赖的urllib3对证书格式要求更严格,确认
server.key是未加密状态;如果私钥有密码,需要修改cert参数为cert=("server.crt", ("server.key", "your_password"))。同时确保CA.pem包含完整的根证书链。 - 指定TLS版本:部分服务器仅支持特定TLS版本,curl默认使用的版本可能和Requests不同,可强制指定兼容的版本:
import requests from requests.adapters import HTTPAdapter from urllib3.poolmanager import PoolManager import ssl class TLSAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2 # 可根据服务器支持情况改为TLSv1_3 ) session = requests.Session() session.mount("https://", TLSAdapter()) # 使用session发起请求 response = session.post(url, headers=headers, json=data, verify=verify, cert=cert) - 禁用代理干扰:如果系统存在代理设置,curl可能自动适配,但Requests会受影响,可在请求中禁用代理:
response = requests.post(url, headers=headers, json=data, verify=verify, cert=cert, proxies={"https": None})
内容的提问来源于stack exchange,提问作者colin chiu
相关产品推荐
相关产品推荐

