python - 如何在 Python 请求中禁用安全证书检查

我正在使用

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

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

最佳答案

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

如果您使用第三方模块并想禁用检查,这里有一个上下文管理器,它可以对 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

这是你如何使用它:

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')

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

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

https://stackoverflow.com/questions/15445981/

相关文章:

linux - 使用 awk 保存修改

python - 在python中通过分隔符拆分字符串

python - python,del或delattr哪个更好?

python - 在 python shell 中按箭头键时看到转义字符

linux - 大量文件的快速 Linux 文件计数

linux - 查找和复制文件

c - C 到毫秒是否有替代 sleep 功能?

python - 递归删除python中的文件夹

linux - Bash循环中的计数器增量不起作用

python - 我在 python 中遇到关键错误