How to use urllib2 to get a webpage using SSLv3 encryption

后端 未结 3 910
甜味超标
甜味超标 2021-01-19 08:40

I\'m using python 2.7 and I\'d like to get the contents of a webpage that requires sslv3. Currently when I try to access the page I get the error SSL23_GET_SERVER_HELLO, and

3条回答
  •  不知归路
    2021-01-19 09:25

    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

提交回复
热议问题