Python 3 urllib 忽略 SSL 证书验证 [英] Python 3 urllib ignore SSL certificate verification
问题描述
我有一个用于测试的服务器设置,带有自签名证书,并希望能够对其进行测试.
I have a server setup for testing, with a self-signed certificate, and want to be able to test towards it.
在 Python 3 版本的 urlopen
中如何忽略 SSL 验证?
How do you ignore SSL verification in the Python 3 version of urlopen
?
我发现的所有相关信息都是关于 urllib2
或 Python 2 的.
All information I found regarding this is regarding urllib2
or Python 2 in general.
urllib
在 python 3 中从 urllib2
改变:
urllib
in python 3 has changed from urllib2
:
Python 2, urllib2: urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])
https://docs.python.org/2/library/urllib2.html#urllib2.urlopen
Python 3:urllib.request.urlopen(url[, data][, timeout])
https://docs.python.org/3.0/library/urllib.request.html?highlight=urllib#urllib.request.urlopen
所以我知道这可以通过以下方式在 Python 2 中完成.但是 Python 3 urlopen
缺少上下文参数.
So I know this can be done in Python 2 in the following way. However Python 3 urlopen
is missing the context parameter.
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)
是的,我知道这是个坏主意.这仅用于在私人服务器上进行测试.
And yes I know this is a bad idea. This is only meant for testing on a private server.
我在 Python 3 文档或任何其他问题中找不到应该如何完成此操作.即使是明确提到 Python 3 的那些,仍然有 urllib2/Python 2 的解决方案.
I could not find how this is supposed to be done in the Python 3 documentation, or in any other question. Even the ones explicitly mentioning Python 3, still had a solution for urllib2/Python 2.
推荐答案
接受的答案只是建议使用 python 3.5+,而不是直接回答.它会引起混乱.
The accepted answer just gave advise to use python 3.5+, instead of direct answer. It causes confusion.
对于寻求直接答案的人,这里是:
For someone looking for a direct answer, here it is:
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:
Alternatively, if you use requests
library, it has much better API:
import requests
with open(file_name, 'wb') as f:
resp = requests.get(url_string, verify=False)
f.write(resp.content)
答案复制自这篇文章(感谢@falsetru):如何在python 3.x中禁用ssl检查?
The answer is copied from this post (thanks @falsetru): How do I disable the ssl check in python 3.x?
这两个问题应该合并.
这篇关于Python 3 urllib 忽略 SSL 证书验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!