Python 3 urllib忽略SSL证书验证

Joa*_*kim 16 python ssl ssl-certificate python-3.x

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

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

我发现的关于此的所有信息都与urllib2Python 2 有关.

urllib在python 3中已从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:https : urllib.request.urlopen(url[, data][, timeout]) //docs.python.org/3.0/library/urllib.request.html?highlight=urllib#urllib.request.urlopen

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

nng*_*eek 22

接受的答案只是建议使用 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)
Run Code Online (Sandbox Code Playgroud)

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

import requests

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

答案是从这篇文章中复制的(感谢@ falsetru):如何在 python 3.x 中禁用 ssl 检查?

这两个问题应该合并。


Muh*_*hir 5

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

  • 您可以更改默认上下文:`ssl._create_default_https_context = ssl._create_unverified_context`,并且根本不需要ctx。 (6认同)
  • 谢谢@AstraSerg,我认为您的评论值得转换为单独的答案。 (2认同)