Python请求中的SSL错误

时间:2016-07-20 19:59:30

标签: python ssl request

我正在尝试使用Python向API发出请求,但我收到了 SSL错误。我到处搜索它,但似乎无法找到解决办法。

这是我在虚拟环境中安装的版本:

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 26 2016, 12:10:39) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8zg 14 July 2015'

我正在尝试使用我在this blog上找到的代码:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl
import requests

class SSLAdapter(HTTPAdapter):
    '''An HTTPS Transport Adapter that uses an arbitrary SSL version.'''
    def __init__(self, ssl_version=None, **kwargs):
        self.ssl_version = ssl_version

        super(SSLAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=self.ssl_version)

if __name__ == '__main__':
    url = 'https://msesandbox.cisco.com:8081/api/location/v2/clients?sortBy=lastLocatedTime:DESC'
    s = requests.Session()
    s.mount("https://", SSLAdapter(ssl.PROTOCOL_SSLv2))
    response = s.get(url) #line that trigger the mistake.
    print (response)

这是输出:

Traceback (most recent call last):
  File "/path/to/file", line 23, in <module>
    response = s.get(url)
  File "/Users/rafacarv/Environments/python2_7_12_cmx/venv/lib/python2.7/site-packages/requests/sessions.py", line 487, in get
    return self.request('GET', url, **kwargs)
  File "/Users/rafacarv/Environments/python2_7_12_cmx/venv/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/rafacarv/Environments/python2_7_12_cmx/venv/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/Users/rafacarv/Environments/python2_7_12_cmx/venv/lib/python2.7/site-packages/requests/adapters.py", line 477, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)

我还尝试使用我在其他question上找到的建议,其中包含使用 requests_toolbelt 包,但没有运气。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

  

msesandbox.cisco.com:8081

此服务器仅支持TLS 1.2,即不支持TLS 1.0或更差。

  

'OpenSSL 0.9.8zg 2015年7月14日'

此OpenSSL版本尚不支持TLS 1.2。至少你需要OpenSSL 1.0.1。