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

我在用

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

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

825273 次浏览

的文档:

requests也可以忽略验证SSL证书 verify to False.

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

注意,一旦离开上下文管理器,此代码将关闭所有处理修补过的请求的打开适配器。这是因为请求维护每个会话的连接池,证书验证只发生一次每个连接,所以会发生意想不到的事情:

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

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)

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

import requests


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

要添加到搅拌机的回答,您可以使用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

也可以使用环境变量:

export CURL_CA_BUNDLE=""

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

import ssl


ssl._create_default_https_context = ssl._create_unverified_context

不用于生产

编辑,评论来自@Misty

< p >不工作。Requests现在使用urllib3,它创建自己的 SSLContext。你可以重写cert_reqs而不是

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

什么对我有用

由于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

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

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

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

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

python 3.6 +

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