如何禁用 Python 请求中的安全证书检查 [英] How do I disable the security certificate check in Python requests

查看:22
本文介绍了如何禁用 Python 请求中的安全证书检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

导入请求requests.post(url='https://foo.com', data={'bar':'baz'})

但我收到一个 request.exceptions.SSLError.该网站的证书已过期,但我没有发送敏感数据,因此对我来说无关紧要.我想有一个像verifiy=False"这样的参数我可以使用,但我似乎找不到它.

解决方案

来自 文档:

<块引用>

requests 也可以忽略验证 SSL 证书,如果你设置verify 为 False.

<预><代码>>>>requests.get('https://kennethreitz.com', verify=False)<响应[200]>

如果您正在使用第三方模块并希望禁用检查,这里有一个上下文管理器,可以修补 requests 并更改它以便 verify=False是默认值并抑制警告.

导入警告导入上下文库进口请求从 urllib3.exceptions 导入 InsecureRequestWarningold_merge_environment_settings = requests.Session.merge_environment_settings@contextlib.contextmanagerdef no_ssl_verification():opens_adapters = set()def merge_environment_settings(self, url, proxies, stream, verify, cert):# 每个连接只验证一次,所以我们需要关闭# 完成后所有打开的适配器.否则,影响# verify=False 在上下文管理器结束后仍然存在.open_adapters.add(self.get_adapter(url))settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)设置['验证'] = False返回设置requests.Session.merge_environment_settings = merge_environment_settings尝试:使用 warnings.catch_warnings():warnings.simplefilter('ignore', InsecureRequestWarning)屈服最后:requests.Session.merge_environment_settings = old_merge_environment_settings对于open_adapters 中的适配器:尝试:适配器关闭()除了:经过

这是你如何使用它:

 with no_ssl_verification():requests.get('https://wrong.host.badssl.com/')打印('它有效')requests.get('https://wrong.host.badssl.com/', verify=True)print('即使你试图强迫它')requests.get('https://wrong.host.badssl.com/', verify=False)打印('它重置回来')session = requests.Session()session.verify = True使用 no_ssl_verification():session.get('https://wrong.host.badssl.com/', verify=True)print('即使在这里也能工作')尝试:requests.get('https://wrong.host.badssl.com/')除了 requests.exceptions.SSLError:打印('它坏了')尝试:session.get('https://wrong.host.badssl.com/')除了 requests.exceptions.SSLError:print('这里又断了')

请注意,一旦您离开上下文管理器,此代码将关闭处理修补请求的所有打开的适配器.这是因为请求维护每个会话的连接池,并且每个连接只进行一次证书验证,因此会发生这样的意外:

<预><代码>>>>进口请求>>>session = requests.Session()>>>session.get('https://wrong.host.badssl.com/', verify=False)/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: 正在发出未经验证的 HTTPS 请求.强烈建议添加证书验证.请参阅:https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings不安全请求警告)<响应[200]>>>>session.get('https://wrong.host.badssl.com/', verify=True)/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: 正在发出未经验证的 HTTPS 请求.强烈建议添加证书验证.请参阅:https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings不安全请求警告)<响应[200]>

I am using

import requests
requests.post(url='https://foo.com', data={'bar':'baz'})

but I get a request.exceptions.SSLError. The website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me. I would imagine there is an argument like 'verifiy=False' that I could use, but I can't seem to find it.

解决方案

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.com/')
    print('It works')

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

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

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

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

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

try:
    session.get('https://wrong.host.badssl.com/')
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.com/', 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.com/', 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 请求中的安全证书检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆