获取 SSL:使用带有 Python 请求的代理时的 CERTIFICATE_VERIFY_FAILED

问题描述 投票:0回答:3

我正在尝试使用 requests 库在 python 中实现代理,但我一遍又一遍地收到相同的错误。这是我的代码:

proxies = {
        'http': 'http://127.0.0.1:24000',
        'https': 'https://127.0.0.1:24000',
    }
    resp = requests.get('https://api.myip.com', proxies=proxies)
    print(resp.text)

我正在使用 Bright Data 的代理管理器,我怀疑我的代理实现是错误的。我收到的错误是:

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.myip.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)')))

我尝试过在网上找到的解决方案,例如 verify=false,它适用于此链接,但不适用于我需要访问的其他链接,这就是为什么我正在寻找更安全的解决方案。

python ssl python-requests
3个回答
3
投票

如果您有自签名证书和密钥的副本,您可以按如下方式修改代码:

proxies = {
    'http': 'http://127.0.0.1:24000',
    'https': 'http://127.0.0.1:24000',
}

certificate_path = os.path.join(CACERT_PATH, 'cacert.pem')
key_path = os.path.join(CACERT_KEY, 'cacert.key')

resp = requests.get('https://api.myip.com',
                    proxies=proxies,
                    cert=(certificate_path, key_path))
print(resp.text)

0
投票

如果您在公司代理背后遇到此问题,那么您看到的问题是请求库认为存在中间人攻击。您可以通过 REQUEST_CA_BUNDLE 环境变量添加自定义证书,这将告诉请求信任您的代理不是攻击者。

向您的 IT 团队索要证书,他们将为您提供 pem、crt 或类似文件。解压它,然后按照本页中的步骤将其映射到环境变量。


-2
投票

verify=False
是一种方法,但禁用这些警告的更好方法是使用以下方法:

import urllib3

urllib3.disable_warnings()
© www.soinside.com 2019 - 2024. All rights reserved.