ssl证书验证的问题

对于https请求,是需要ssl证书验证的请求的,所以如果在请求时如果不带ssl证书,那么可以忽略证书的验证

有三种方法去实现:

1、Requests请求:

在文档中可以看到:http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

Requests 可以为 HTTPS 请求验证 SSL 证书,就像 web 浏览器一样。要想检查某个主机的 SSL 证书,你可以使用 verify 参数:

如果你没有设置ssl证书,那就忽略证书:

如果你将 verify 设置为 False,Requests 也能忽略对 SSL 证书的验证。

 requests.get('https://kennethreitz.com', verify=False)

因为默认情况下,是verify是为Ture

2、urllib2.urlopen()

使用urllib的时候,就需要关闭证书的验证,在官网文档可以看到

https://www.python.org/dev/peps/pep-0476/

import ssl

# This restores the same behavior as before.
context = ssl._create_unverified_context()
urllib.urlopen("https://no-valid-cert", context=context)

 

以上几行代码就可以跳过ssl证书的验证了。

3、urllib3的到来

>>> import urllib3.contrib.pyopenssl
>>> urllib3.contrib.pyopenssl.inject_into_urllib3()

Finally, you can create a PoolManager that verifies certificates when performing requests:

>>> import certifi
>>> import urllib3
>>> http = urllib3.PoolManager(
...     cert_reqs='CERT_REQUIRED',
...     ca_certs=certifi.where())

The PoolManager will automatically handle certificate verification and will raise SSLErrorif verification fails:

>>> http.request('GET', 'https://google.com')
(No exception)
>>> http.request('GET', 'https://expired.badssl.com')
urllib3.exceptions.SSLError ...

最后一点就是

Requests 默认附带了一套它信任的根证书,来自于 Mozilla trust store。然而它们在每次 Requests 更新时才会更新。这意味着如果你固定使用某一版本的 Requests,你的证书有可能已经 太旧了。

从 Requests 2.4.0 版之后,如果系统中装了 certifi 包,Requests 会试图使用它里边的 证书。这样用户就可以在不修改代码的情况下更新他们的可信任证书。

为了安全起见,我们建议你经常更新 certifi!

posted @ 2017-03-23 12:02  你若精彩,蝴蝶自来  阅读(2258)  评论(0编辑  收藏  举报