我正在编写一个简单的脚本,涉及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

当前回答

要使用的CA文件的名称可以通过验证:

cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
r = requests.get(url, verify=cafile)

如果使用verify=True,则requests使用自己的CA集,该CA集可能没有签署您的服务器证书的CA。

其他回答

如果你有一个依赖于请求的库,你不能修改验证路径(比如pyvmomi),那么你必须找到cacert。. pem和请求捆绑在一起,并在那里追加您的CA。下面是查找cacert的通用方法。pem位置:

窗户

C:\>python -c "import requests; print requests.certs.where()"
c:\Python27\lib\site-packages\requests-2.8.1-py2.7.egg\requests\cacert.pem

linux

#  (py2.7.5,requests 2.7.0, verify not enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/lib/python2.7/dist-packages/certifi/cacert.pem

#  (py2.7.10, verify enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/local/lib/python2.7/dist-packages/requests/cacert.pem

顺便说一句。@requests-devs,把自己的cacerts和request捆绑在一起真的很讨厌…特别是事实是,您似乎没有首先使用系统ca存储,这是没有记录在任何地方。

更新

在使用库且无法控制ca-bundle位置的情况下,你也可以显式地将ca-bundle位置设置为主机范围内的ca-bundle:

REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-bundle.crt python -c "import requests; requests.get('https://somesite.com')";

要使用的CA文件的名称可以通过验证:

cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
r = requests.get(url, verify=cafile)

如果使用verify=True,则requests使用自己的CA集,该CA集可能没有签署您的服务器证书的CA。

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

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

使用OpenSSL 1.0.2g 2016年3月1日

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

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

有些服务器没有Letsencrypt的可信根证书。

例如,假设下面的url指向的服务器受到Letsencrypt SSL的保护。

requests.post(url, json=data)

此请求可能使用[SSL: CERTIFICATE_VERIFY_FAILED]失败,因为请求服务器没有Letsencrypt的根证书。

当发生这种情况时,请从下面的链接下载活动自签名的“pem”证书。

https://letsencrypt.org/certificates/。(在撰写本文时,ISRG根X1处于活动状态)

现在,在verify参数中使用它,如下所示。

requests.post(url, json=data, verify='path-to/isrgrootx1.pem')

如果从另一个包调用请求,则添加选项是不可行的。在这种情况下,将证书添加到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

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