Python 3 urllib 忽略 SSL 证书验证

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

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

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

我找到的所有关于此的信息一般都是关于 urllib2 或 Python 2。

python 3 中的

urllib 已从 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 缺少上下文参数。

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)

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

我无法在 Python 3 文档或任何其他问题中找到应该如何完成此操作。即使是那些明确提到 Python 3 的人,仍然有针对 urllib2/Python 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?

这两个问题应该合并。

关于Python 3 urllib 忽略 SSL 证书验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36600583/

相关文章:

C 表达式的 Python 等价物

python - 为什么我的计算机中的 Python 列表不能容纳超过 693 个数字?

python - 在 Python 中部署 Tensorflow 模型

ssl - 在 NGINX-Ingress 上使用 session 关联性 (Cookie) 和 SSL 直通

ssl - Tls 握手失败,即使密码套件是通用的

python - 使用 Genius API

python - 操作系统错误 : [Errno 12] Cannot allocate memory when using python multiprocessing Pool

客户端-服务器应用程序上的 Linux 套接字输入通知

python - 'PySide2.QtCore.Signal' 对象没有属性 'connect'

python-3.x - 当最大像素值小于65535时,如何规范化uint16图像并将其转换为uint8?