在Python请求中捕获客户端/服务器TLS版本

时间:2017-10-02 19:02:37

标签: python ssl python-requests

是否可以使用Python请求模块查看与服务器协商的TLS版本? 类似于openssl s_client -connect将返回的内容

---
No client certificate CA names sent
---
SSL handshake has read 3043 bytes and written 375 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.1
    Cipher    : ECDHE-RSA-AES256-SHA
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None

1 个答案:

答案 0 :(得分:0)

如果您只想一次做一次测试就复制另一个答案的核心,https://stackoverflow.com/a/55462022/6368697,猴子补丁就足够了(否则,请阅读我的其余答案,其中提供了一个正确的实现传输适配器,以及正确显示收到的证书):

import requests
from requests.packages.urllib3.connection import VerifiedHTTPSConnection

SOCK = None

_orig_connect = requests.packages.urllib3.connection.VerifiedHTTPSConnection.connect

def _connect(self):
    global SOCK
    _orig_connect(self)
    SOCK = self.sock

requests.packages.urllib3.connection.VerifiedHTTPSConnection.connect = _connect

requests.get('https://yahoo.com')
tlscon = SOCK.connection
print 'Cipher is %s/%s' % (tlscon.get_cipher_name(), tlscon.get_cipher_version())
print 'Remote certificates: %s' % (tlscon.get_peer_certificate())
print 'Protocol version: %s' % tlscon.get_protocol_version_name()

这将产生:

Cipher is ECDHE-RSA-AES128-GCM-SHA256/TLSv1.2
Remote certificates: <OpenSSL.crypto.X509 object at 0x10c60e310>
Protocol version: TLSv1.2