如何禁用 Python 请求中的安全证书检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15445981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:07:47  来源:igfitidea点击:

How do I disable the security certificate check in Python requests

pythonhttpspython-requests

提问by Paul Draper

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.

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

采纳答案by Blender

From the documentation:

文档

requestscan also ignore verifying the SSL certificate if you set verifyto False.

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

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

>>> 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 requestsand changes it so that verify=Falseis the default and suppresses the warning.

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

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]>

回答by efrenfuentes

Use requests.packages.urllib3.disable_warnings()and verify=Falseon requestsmethods.

使用requests.packages.urllib3.disable_warnings()verify=Falseonrequests方法。

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)

回答by Ruslan Khyurri

If you want to send exactly post request with verify=False option, fastest way is to use this code:

如果您想使用 verify=False 选项准确发送发布请求,最快的方法是使用以下代码:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

回答by Stevoisiak

To add to Blender's answer, you can disable SSL for all requests using Session.verify = False

要添加到Blender 的答案中,您可以使用禁用所有请求的 SSLSession.verify = False

import requests

session = requests.Session()
session.verify = False
session.post(url='https://foo.com', data={'bar':'baz'})

Note that urllib3, (which Requests uses), strongly discouragesmaking unverified HTTPS requests and will raise an InsecureRequestWarning.

请注意urllib3,(请求使用的)强烈反对发出未经验证的 HTTPS 请求,并且会引发InsecureRequestWarning.

回答by Stan Gabenov

Also can be done from the environment variable:

也可以从环境变量中完成:

export CURL_CA_BUNDLE=""