我得到以下错误:

Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in        __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in  run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Matthew/Desktop/Skypebot 2.0/bot.py", line 271, in process
info = urllib2.urlopen(req).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

下面是导致这个错误的代码:

if input.startswith("!web"):
    input = input.replace("!web ", "")      
    url = "https://domainsearch.p.mashape.com/index.php?name=" + input
    req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXX' })
    info = urllib2.urlopen(req).read()
    Message.Chat.SendMessage ("" + info)

我正在使用的API要求我使用HTTPS。我怎样才能让它绕过验证呢?


当前回答

对于任何使用mechanize遇到这个问题的人,下面是如何将相同的技术应用到mechanize Browser实例:

br = mechanize.Browser()
context = ssl._create_unverified_context()
br.set_ca_data(context=context)

其他回答

import requests
requests.packages.urllib3.disable_warnings()

import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context

从这里拍摄https://gist.github.com/michaelrice/a6794a017e349fc65d01

如果只想绕过验证,可以创建一个新的SSLContext。默认情况下,新创建的上下文使用CERT_NONE。

如17.3.7.2.1节所述,请注意这一点

当直接调用SSLContext构造函数时,CERT_NONE是默认值。由于它不验证另一个对等体,因此它可能是不安全的,特别是在客户端模式下,大多数时候您希望确保与之通信的服务器的真实性。因此,在客户端模式下,强烈建议使用CERT_REQUIRED。

但如果你只是想让它现在工作,你可以做以下事情,你也必须导入ssl:

input = input.replace("!web ", "")      
url = "https://domainsearch.p.mashape.com/index.php?name=" + input
req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' })
gcontext = ssl.SSLContext()  # Only for gangstars
info = urllib2.urlopen(req, context=gcontext).read()
Message.Chat.SendMessage ("" + info)

这应该可以解决您的问题,但您并没有真正解决任何问题,但您不会看到[SSL: CERTIFICATE_VERIFY_FAILED],因为您现在没有验证证书!

为了补充以上内容,如果您想了解更多关于为什么会遇到这些问题的信息,请参阅PEP 476。

这个PEP建议在默认情况下启用X509证书签名的验证,以及Python的HTTP客户端的主机名验证,并在每次调用的基础上选择退出。此更改将应用于Python 2.7、Python 3.4和Python 3.5。

有一个建议选择退出,这与我上面的建议没有什么不同:

import ssl

# This restores the same behavior as before.
context = ssl._create_unverified_context()
urllib.urlopen("https://no-valid-cert", context=context)

它还提供了一个非常不推荐的monkeypatching选项,这在python中并不常见:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

它用创建未经验证的上下文的函数覆盖用于创建上下文的默认函数。

请注意PEP中所述:

This guidance is aimed primarily at system administrators that wish to adopt newer versions of Python that implement this PEP in legacy environments that do not yet support certificate verification on HTTPS connections. For example, an administrator may opt out by adding the monkeypatch above to sitecustomize.py in their Standard Operating Environment for Python. Applications and libraries SHOULD NOT be making this change process wide (except perhaps in response to a system administrator controlled configuration setting).

如果你想读一篇关于为什么不验证证书是不好的软件的论文,你可以在这里找到它!

我也遇到了类似的问题,不过我在Python 3.4、3.5和3.6中使用了urllib.request.urlopen。(这是Python 3中urllib2的一部分,根据Python 2的urllib2文档页面头部的注释。)

我的解决方案是pip install certifi来安装certifi,它有:

... 一个精心策划的根证书集合,用于验证SSL证书的可信度,同时验证TLS主机的身份。

然后,在我的代码中,我之前只有:

import urllib.request as urlrq

resp = urlrq.urlopen('https://example.com/bar/baz.html')

我将其修改为:

import urllib.request as urlrq
import certifi

resp = urlrq.urlopen('https://example.com/bar/baz.html', cafile=certifi.where())

如果我读取urllib2。Urlopen文档正确,它也有一个cafile参数。所以,urllib2.urlopen([…], certificate .where())可能也适用于Python 2.7。


更新(2020-01-01):自Python 3.6起,已弃用urlopen的cafile参数,取而代之的应该是指定context参数。我发现以下功能在3.5到3.8版本中同样有效:

import urllib.request as urlrq
import certifi
import ssl

resp = urlrq.urlopen('https://example.com/bar/baz.html', context=ssl.create_default_context(cafile=certifi.where()))

The SSL: CERTIFICATE_VERIFY_FAILED error could also occur because an Intermediate Certificate is missing in the ca-certificates package on Linux. For example, in my case the intermediate certificate "DigiCert SHA2 Secure Server CA" was missing in the ca-certificates package even though the Firefox browser includes it. You can find out which certificate is missing by directly running the wget command on the URL causing this error. Then you can search for the corresponding link to the CRT file for this certificate from the official website (e.g. https://www.digicert.com/digicert-root-certificates.htm in my case) of the Certificate Authority. Now, to include the certificate that is missing in your case, you may run the below commands using your CRT file download link instead:

wget https://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt

mv DigiCertSHA2SecureServerCA.crt DigiCertSHA2SecureServerCA.der

openssl x509 -inform DER -outform PEM -in DigiCertSHA2SecureServerCA.der -out DigicertSHA2SecureServerCA.pem.crt

sudo mkdir /usr/share/ca-certificates/extra

sudo cp DigicertSHA2SecureServerCA.pem.crt /usr/share/ca-certificates/extra/

sudo dpkg-reconfigure ca-certificates

在此之后,您可以再次使用wget测试URL,也可以使用python urllib包进行测试。详情请参考:https://bugs.launchpad.net/ubuntu/+source/ca-certificates/+bug/1795242

如果你在vCenter 6上,你应该将你vCenter的vmware证书颁发机构证书添加到你的操作系统的受信任CA列表中。要下载证书,请执行以下操作

打开Web浏览器。 导航到https:// 在右下角单击“下载受信任的根CA”链接

在Fedora

解压缩并将扩展名从.0更改为.cer 将其复制到/etc/pki/ca-trust/source/anchors/ 执行update-ca-trust命令。

链接:

https://virtualizationreview.com/articles/2015/04/02/install-root-self-signed-certificate-vcenter-6.aspx?m=1 http://forums.fedoraforum.org/showthread.php?t=293856