How to use urllib2 to get a webpage using SSLv3 encryption

廉价感情. 提交于 2019-12-01 18:44:29

I realize this response is a few years too late, but I also ran into the same problem, and didn't want to depend on libcurl being installed on a machine where I ran this. Hopefully, this will be useful to those who find this post in the future.

The problem is that httplib.HTTPSConnection.connect doesn't have a way to specify SSL context or version. You can overwrite this function before you hit the meat of your script for a quick solution.

An important consideration is that this workaround, as discussed above, will not verify the validity of the server's certificate.

import httplib
import socket
import ssl
import urllib2

def connect(self):
    "Connect to a host on a given (SSL) port."

    sock = socket.create_connection((self.host, self.port),
                                    self.timeout, self.source_address)
    if self._tunnel_host:
        self.sock = sock
        self._tunnel()

    self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)

httplib.HTTPSConnection.connect = connect

opener = urllib2.build_opener()
f = opener.open('https://www.google.com/')

*Note: this alternate connect() function was copy/pasted from httplib.py, and simply modified to specify the ssl_version in the wrap_socket() call

Timmy O'Mahony

SSL should be handled automatically as long as you have the SSL libraries installed on your server (i.e. you shouldn't have to specificially add it as a handler)

http://docs.python.org/library/urllib2.html#urllib2.build_opener

If the Python installation has SSL support (i.e., if the ssl module can be imported), HTTPSHandler will also be added.

Also, note that urllib and urllib2 have been merged in python 3 so their approach is a little different

Since I was unable to do this using urllib2, I eventually gave in and moved to using the libCurl bindings like @Bruno had suggested in the comments to pastylegs answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!