Python 3 urllib忽略SSL证书验证

时间:2016-04-13 13:53:04

标签: python python-3.x ssl ssl-certificate

我有一个用于测试的服务器设置,带有自签名证书,并希望能够对其进行测试。

如何忽略Python {3}版{/ 1}}中的SSL验证?

我发现的所有相关信息都与urlopen或Python 2有关。

python 3中的

urllib2已从urllib更改为

Python 2,urllib2 urllib2

https://docs.python.org/2/library/urllib2.html#urllib2.urlopen

Python 3 urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]]) https://docs.python.org/3.0/library/urllib.request.html?highlight=urllib#urllib.request.urlopen

所以我知道这可以通过以下方式在Python 2中完成。但是Python 3 urllib.request.urlopen(url[, data][, timeout])缺少上下文参数。

urlopen

是的,我知道这是一个坏主意。这仅适用于在私人服务器上进行测试。

我无法找到如何在Python 3文档或任何其他问题中完成此操作。即使是明确提到Python 3的人,仍然有urllib2 / Python 2的解决方案。

2 个答案:

答案 0 :(得分:5)

Python 3.0到3.3没有上下文参数,它是在Python 3.4中添加的。因此,您可以将Python版本更新为3.5以使用上下文。

答案 1 :(得分:2)

接受的答案只是建议使用python 3.5+,而不是直接答案。会引起混乱。

对于寻求直接答案的人,这里是:

import ssl
import urllib.request

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

with urllib.request.urlopen(url_string, context=ctx) as f:
    f.read(300)

或者,如果您使用requests库,则它具有更好的API:

import requests

with open(file_name, 'wb') as f:
    resp = requests.get(url_string, verify=False)
    f.write(resp.content)

答案是从这篇文章中复制的(感谢@ falsetru):How do I disable the ssl check in python 3.x?

这两个问题应该合并。

相关问题