我正在编写一个简单的脚本,涉及CAS、jspring安全检查、重定向等。我想使用Kenneth Reitz的python请求,因为它是一个伟大的作品!然而,CAS需要通过SSL进行验证,所以我必须先通过这一步。我不知道Python请求想要什么?这个SSL证书应该驻留在哪里?

Traceback (most recent call last):
  File "./test.py", line 24, in <module>
  response = requests.get(url1, headers=headers)
  File "build/bdist.linux-x86_64/egg/requests/api.py", line 52, in get
  File "build/bdist.linux-x86_64/egg/requests/api.py", line 40, in request
  File "build/bdist.linux-x86_64/egg/requests/sessions.py", line 209, in request 
  File "build/bdist.linux-x86_64/egg/requests/models.py", line 624, in send
  File "build/bdist.linux-x86_64/egg/requests/models.py", line 300, in _build_response
  File "build/bdist.linux-x86_64/egg/requests/models.py", line 611, in send
requests.exceptions.SSLError: [Errno 1] _ssl.c:503: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

当前回答

正如@Rafael Almeida所提到的,您遇到的问题是由不受信任的SSL证书引起的。在我的例子中,我的服务器不信任SSL证书。为了在不影响安全性的情况下解决这个问题,我下载了证书,并将其安装到服务器上(只需双击.crt文件,然后安装证书…)。

其他回答

如果请求调用隐藏在代码深处的某个地方,而你不想安装服务器证书,那么,仅用于调试目的,可以monkeypatch请求:

import requests.api
import warnings


def requestspatch(method, url, **kwargs):
    kwargs['verify'] = False
    return _origcall(method, url, **kwargs)

_origcall = requests.api.request
requests.api.request = requestspatch
warnings.warn('Patched requests: SSL verification disabled!')

永远不要在生产中使用!

经过几个小时的调试后,我只能使用以下包来工作:

requests[security]==2.7.0  # not 2.18.1
cryptography==1.9  # not 2.0

使用OpenSSL 1.0.2g 2016年3月1日

如果没有这些包,verify=False将无法工作。

我希望这能帮助到一些人。

如果从另一个包调用请求,则添加选项是不可行的。在这种情况下,将证书添加到cacert包是直接的路径,例如,我必须添加“StartComClass1 Primary Intermediate Server CA”,为此我将根证书下载到StartComClass1.pem中。鉴于我的virtualenv被命名为caldav,我添加了证书:

cat StartComClass1.pem >> .virtualenvs/caldav/lib/python2.7/site-packages/pip/_vendor/requests/cacert.pem
cat temp/StartComClass1.pem >> .virtualenvs/caldav/lib/python2.7/site-packages/requests/cacert.pem

其中一个可能就够了,我没有检查

我不得不从Python 3.4.0升级到3.4.6

pyenv virtualenv 3.4.6 myvenv
pyenv activate myvenv
pip install -r requirements.txt

我遇到了类似或相同的认证验证问题。我读到过小于1.0.2的OpenSSL版本,请求所依赖的版本有时会在验证强证书时遇到麻烦(见这里)。CentOS 7似乎使用了1.0.1e,这似乎有问题。

我不确定如何在CentOS上解决这个问题,所以我决定允许较弱的1024bit CA证书。

import certifi # This should be already installed as a dependency of 'requests'
requests.get("https://example.com", verify=certifi.old_where())