Python 3 urllib忽略SSL证书验证

2024-04-19 11:55:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何忽略Python 3版本urlopen中的SSL验证?

我找到的关于这个的所有信息都是关于urllib2或Python 2的。

python 3中的urllib已从urllib2更改为:

Python 2,urllib2urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

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

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

所以我知道在Python 2中可以通过以下方式完成。但是Python 3urlopen缺少上下文参数。

import urllib2
import ssl

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

urllib2.urlopen("https://your-test-server.local", context=ctx)

是的,我知道这是个坏主意。这只用于在私有服务器上测试。

我在Python3文档中或其他任何问题中都找不到这应该如何实现。即使是那些明确提到Python 3的人,仍然有一个urllib2/Python 2的解决方案。


Tags: httpsorg服务器urlssldocsdatarequest
2条回答

接受的答案只是建议使用Python3.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?

这两个问题应该合并起来。

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

相关问题 更多 >