我想在urllib2中选择传输层安全协议

Abh*_*rma 6 openssl urllib2 python-2.7 sslv2

我想在Python 2.7中使用urllib2.urlopen()选择用于打开https链接的传输层协议

与我们使用openssl实用程序可以执行的操作类似:

openssl s_client -connect www.google.com:443 -ssl2
openssl s_client -connect www.google.com:443 -ssl3
openssl s_client -connect www.google.com:443 -tls1
Run Code Online (Sandbox Code Playgroud)

动机是不使用ssl2协议导致大多数服务器中的握手问题.urllib2似乎使用SSLv23协议,它使用SSLv2或SSLv3与某种机制的下降.有些情况会导致握手问题

jfs*_*jfs 8

更新: 因为Python 2.7.9,你可以通过的SSLContext指定TLS协议,以urlopen()功能:

import ssl
import urllib2

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
# other settings (see ssl.create_default_context() implementation)
urllib2.urlopen('https://example.com', context=context).close()
Run Code Online (Sandbox Code Playgroud)

老答案:

httplib.HTTPSConnection并且urllib2.HTTPSHandler不允许更改ssl版本,但 ssl.wrap_socket()确实如此.

你可以定义自己的HTTPSHandler,允许你传递任意参数,ssl.wrap_socket()例如urllib2_ssl.py:

>>> import ssl
>>> import urllib2
>>> import urllib2_ssl # https://gist.github.com/zed/1347055
>>> opener = urllib2.build_opener(urllib2_ssl.HTTPSHandler(
...     ssl_version=ssl.PROTOCOL_TLSv1, #XXX you need to modify urllib2_ssl
...     ca_certs='cacert.pem')) # http://curl.haxx.se/ca/cacert.pem.bz2
>>> opener.open('https://example.com/').read()
Run Code Online (Sandbox Code Playgroud)