关于EOF occurred in violation of protocol (_ssl.c:661)的解决办法

关于EOF occurred in violation of protocol (_ssl.c:661)的解决办法

直接上代码(python版本2.7)
`import requests
r = requests.get(‘https://www.zjkill.com/news/‘)
r.encoding = ‘utf8’
print r.text
print r.status_code,r.url`
报错

requests.exceptions.SSLError: (“bad handshake: SysCallError(-1, ‘Unexpected EOF’)”,)

经过一番查找,发现是requests不在支持3DES stream cipher。

下面是解决办法,注意ruquests版本2.11及以下的

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

class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)
s = requests.Session()
s.mount('https://', MyAdapter())
r = requests.get('https://www.zjkill.com/news/')
r.encoding = 'utf8'
print r.text

如果requests版本是2.12及以上

import requests
                from requests.adapters import HTTPAdapter
                from requests.packages.urllib3.util.ssl_ import create_urllib3_context
                CIPHERS = (
                    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
                    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
                    '!eNULL:!MD5'
                )

                class DESAdapter(HTTPAdapter):
                    """
                    A TransportAdapter that re-enables 3DES support in Requests.
                    """

                    def init_poolmanager(self, *args, **kwargs):
                        context = create_urllib3_context(ciphers=CIPHERS)
                        kwargs['ssl_context'] = context
                        return super(DESAdapter, self).init_poolmanager(*args, **kwargs)

                    def proxy_manager_for(self, *args, **kwargs):
                        context = create_urllib3_context(ciphers=CIPHERS)
                        kwargs['ssl_context'] = context
                        return super(DESAdapter, self).proxy_manager_for(*args, **kwargs)

                s = requests.Session()
                s.mount('https://www.zjkill.com/', DESAdapter())
                r = s.get(url)
                r.encoding = 'utf8'
                print r.text

因为我用的python2.7,python3的解决办法就不写,那个更简单,可以自行网上搜索。
附上参考链接Configuring TLS With Requests

    原文作者:吃蛇的鸟
    原文地址: https://segmentfault.com/a/1190000015474782
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞