带有自签名证书的 Python 3 urllib [英] Python 3 urllib with self-signed certificates

查看:70
本文介绍了带有自签名证书的 Python 3 urllib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 从内部服务器下载一些数据.由于它是内部的,因此它使用自签名证书.(我们不想为永远不会出现在野外"的服务器向 Verisign 支付费用.)代码的 Python 2.6 版本运行良好.

I'm attempting to download some data from an internal server using Python. Since it's internal, it uses a self-signed certificate. (We don't want to pay Verisign for servers that will never appear "in the wild.") The Python 2.6 version of the code worked fine.

response = urllib2.urlopen(URL)
data = csv.reader(response)

我现在正在尝试更新到 Python 3.4(长话短说,不要问.)但是,使用 Python 3 的 urllib 失败了:

I'm now trying to update to Python 3.4 (long story, don't ask.) However, using Python 3's urllib fails:

response = urllib.request.urlopen(URL)

它抛出一个 CERTIFICATE_VERIFY_FAILED 错误.

It throws a CERTIFICATE_VERIFY_FAILED error.

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)>

在网上阅读时,显然 Python 2.6 urllib2 不费心去验证证书.某些版本的 urllib 允许将verify=False"传递给方法签名,但这在 Python 3.4 中似乎不起作用.

In reading around the web, apparently Python 2.6 urllib2 doesn't bother to verify certificates. Some versions of urllib allow "verify=False" to be passed to the method signature, but that doesn't appear to work in Python 3.4.

有谁知道我如何解决这个问题?由于公司安全准则,我想避免使用 Requests 包.

Does anyone know how I can get around this? I'd like to avoid using the Requests package because of corporate security guidelines.

推荐答案

urllib.request.urlopen 有一个接受 SSLContext 对象.因此,使用 传递 SSLContext 对象.verify_mode 设置为 ssl.CERT_NONESSLContext.verify_mode = ssl.CERT_NONE 应该等于 verify=False

urllib.request.urlopen has a context keyword parameter that accepts an SSLContext object. So, passing a SSLContext object with .verify_mode set to ssl.CERT_NONE i.e. SSLContext.verify_mode = ssl.CERT_NONE should be equal to verify=False

这篇关于带有自签名证书的 Python 3 urllib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆