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

slhcrj9b  于 2023-01-01  发布在  Python
关注(0)|答案(9)|浏览(258)

我在用

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

但我收到一个request.exceptions.SSLErr。网站的证书过期了,但我没有发送敏感数据,所以这对我来说无关紧要。我本以为有一个类似"verifiy = False"的参数可以使用,但似乎找不到。

qlzsbp2j

qlzsbp2j1#

来自文档:
如果将verify设置为False,requests也可以忽略SSL证书验证。

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

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

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

qij5mzcb2#

requests方法上使用requests.packages.urllib3.disable_warnings()verify=False

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

rsl1atfo3#

要添加到Blender's answer,您可以使用Session.verify = False对所有请求禁用SSL证书验证

import requests

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

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

0yg35tkg

0yg35tkg4#

也可以使用环境变量来完成:

export CURL_CA_BUNDLE=""
xt0899hw

xt0899hw5#

如果你正在写一个scraper,并且真的不关心SSL证书,你可以把它设置为全局的:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

请勿用于生产

编辑,来自@Misty的评论
不起作用。请求现在使用urllib 3,它创建自己的SSLContext。您可以替代cert_reqs

ssl.SSLContext.verify_mode = property(lambda self: ssl.CERT_NONE, lambda self, newval: None)
qxsslcnc

qxsslcnc6#

如果你想发送完全后请求与verify=False选项,最快的方法是使用以下代码:

import requests

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

eqzww0vc7#

什么对我有效Due verify=False Bug

由于session.verify=False上的一个错误导致urllib*忽略
当一个环境变量(CURL_CA_BUNDLE)被设置时,我们把它设置为空。

import requests, os
session = requests.Session()
session.verify = False
session.trust_env = False
os.environ['CURL_CA_BUNDLE']="" # or whaever other is interfering with 
session.post(url='https://example.com', data={'bar':'baz'})

不确定是否需要trust_env

j9per5c4

j9per5c48#

首先导入ssl,然后在你的python脚本文件中用三行代码创建一个变量-

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

我在HTML解析中使用beautifulsoup的一个例子是这样的-

import urllib.request,urllib.parse,urllib.error

from bs4 import BeautifulSoup
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
ej83mcc0

ej83mcc09#

Python 3.6+

import warnings
warnings.filterwarnings("ignore", message="Unverified HTTPS request")

相关问题