python requests.Session 绕过ssl证书验证 [SSL: CERTIFICATE_VERIFY_FAILED]

From the documentation:

requests can also ignore verifying the SSL certificate if you set verify to False.

>>> requests.get('https://kennethreitz.com', verify=False)
<Response [200]>

If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches requests and changes it so that verify=False is the default and suppresses the warning.

import warnings
import contextlib

import requests
from urllib3.exceptions import InsecureRequestWarning

old_merge_environment_settings = requests.Session.merge_environment_settings

@contextlib.contextmanager
def no_ssl_verification():
    opened_adapters = set()

    def merge_environment_settings(self, url, proxies, stream, verify, cert):
        # Verification happens only once per connection so we need to close
        # all the opened adapters once we're done. Otherwise, the effects of
        # verify=False persist beyond the end of this context manager.
        opened_adapters.add(self.get_adapter(url))

        settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
        settings['verify'] = False

        return settings

    requests.Session.merge_environment_settings = merge_environment_settings

    try:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', InsecureRequestWarning)
            yield
    finally:
        requests.Session.merge_environment_settings = old_merge_environment_settings

        for adapter in opened_adapters:
            try:
                adapter.close()
            except:
                pass

Here's how you use it:

with no_ssl_verification():
    requests.get('https://wrong.host.badssl.example/')
    print('It works')

    requests.get('https://wrong.host.badssl.example/', verify=True)
    print('Even if you try to force it to')

requests.get('https://wrong.host.badssl.example/', verify=False)
print('It resets back')

session = requests.Session()
session.verify = True

with no_ssl_verification():
    session.get('https://wrong.host.badssl.example/', verify=True)
    print('Works even here')

try:
    requests.get('https://wrong.host.badssl.example/')
except requests.exceptions.SSLError:
    print('It breaks')

try:
    session.get('https://wrong.host.badssl.example/')
except requests.exceptions.SSLError:
    print('It breaks here again')

Note that this code closes all open adapters that handled a patched request once you leave the context manager. This is because requests maintains a per-session connection pool and certificate validation happens only once per connection so unexpected things like this will happen:

>>> import requests
>>> session = requests.Session()
>>> session.get('https://wrong.host.badssl.example/', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>
>>> session.get('https://wrong.host.badssl.example/', verify=True)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>
Python中处理SSL证书验证失败的错误通常需要检查几个方面。如果你确信服务器证书是有效的,你可以通过以下步骤尝试解决问题: 1. **临时禁用证书验证**(不推荐生产环境): 使用`requests`库时,可以在发起请求前暂时关闭证书验证,示例如下: ```python import requests session = requests.Session() session.verify = False # 禁用证书验证 response = session.get('https://example.com') ``` 2. **忽略特定的SSL错误**: 可以捕获并处理特定的SSL错误,例如: ```python try: response = session.get('https://example.com') except requests.exceptions.SSLError as e: if 'CERTIFICATE_VERIFY_FAILED' in str(e): print("Certificate verification failed.") pass # 或者在这里采取其他处理措施 ``` 3. **更改证书路径**: 如果你知道证书的具体位置,可以指定一个可信的证书目录: ```python session.verify = '/path/to/cert.pem' # 替换为实际的证书文件路径 ``` 4. **安装缺失的根证书**: 如果证书是由自签名证书颁发的,可以将该证书添加到系统证书存储。具体操作依赖于你的Python发行版,比如在Ubuntu上可以用`certutil`工具。 5. **升级Pythonrequests库**: 确保你使用的Pythonrequests库是最新的,因为新版本可能包含了对新证书格式的支持或者修复了已知问题。 6. **配置HTTPS代理**: 如果你正在通过HTTP代理访问网站,确保代理能够正确地验证SSL证书。 请注意,在处理这类问题时,尽量保证你的解决方案不会影响数据安全性,尤其是在处理敏感信息的时候。在生产环境中,建议始终保持默认的证书验证机制,并使用受信任的服务器证书
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子燕若水

吹个大气球

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值