正在尝试加载 SSL 证书:描述符 'load_cert_chain' 需要一个“_ssl._SSLContext”对象但收到了一个 'str'

Attempting to load an SSL Certificate: descriptor 'load_cert_chain' requires a '_ssl._SSLContext' object but received a 'str'

我正在尝试加载证书,以便在下载某些文件时绕过我们的公司防火墙。我使用 urllib2 下载这些文件,并尝试添加证书作为上下文。这曾经工作了一段时间,但现在不再工作了。我收到以下错误:

TypeError: descriptor 'load_cert_chain' requires a '_ssl._SSLContext' object but received a 'str'

Python 网站上的文档说明如下:

SSLContext.load_cert_chain(certfile, keyfile=None, password=None)

Load a private key and the corresponding certificate. The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate’s authenticity. The keyfile string, if present, must point to a file containing the private key in. Otherwise the private key will be taken from certfile as well. See the discussion of Certificates for more information on how the certificate is stored in the certfile.

我的代码如下:

    cert = SSLContext.load_cert_chain('<abs_path_to_PEM_file>')
    scheme, netloc, path, params, query, frag = urlparse(url)
    auth, host = urllib2.splituser(netloc)
    if auth:
        url = urlunparse((scheme, host, path, params, query, frag))
        req = urllib2.Request(url)
        base64string = base64.encodestring(auth)[:-1]
        basic = "Basic " + base64string
        req.add_header("Authorization", basic)
    else:
        req = urllib2.Request(url)
    url_obj = urllib2.urlopen(req, context=cert)
    with open(tmp_path, 'wb') as fp:
        fp.write(url_obj.read())
    return tmp_path, url_obj.info()

那里说certfile参数应该是PEM文件所在路径的字符串。这正是我正在做的,但我收到了这个错误。我很困惑。我在这里做错了什么?

提前致谢!

.load_cert_chain 不是静态方法。您需要实例化一个 SSLContext 对象。在最简单的情况下,这可以通过

方法来完成
ctx = ssl.create_default_context()

然后

ctx.load_default_certs()

然后您可以按如下方式使用它:

url_obj = urllib2.urlopen(req, context=ctx)