【问题标题】:Add SSL CA File Using urllib2使用 urllib2 添加 SSL CA 文件
【发布时间】:2024-01-23 01:16:02
【问题描述】:

我需要能够指定 SSL 证书 CA 根,但能够使用 Python 2.7.10 urllib2 库插入 HTTP cookie

ssl_handler = urllib2.HTTPSHandler()
opener = urllib2.build_opener(ssl_handler)
opener.addheaders.append(("Cookie","foo=blah"))
res = opener.open(https://example.com/some/info)

我知道 urllib2 支持 cafile 参数,我应该在我的代码中哪里使用它?

【问题讨论】:

标签: python ssl ssl-certificate urllib2


【解决方案1】:

urlopen documentation:

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

所以,请尝试:

urllib2.urlopen("https://example.com/some/info", cafile="test_cert.pem")

cxt = ssl.create_default_context(cafile="/path/test_cert.pem")
urllib2.urlopen("https://example.com/some/info", context=cxt)

【讨论】:

  • 我可以使用urllib2.urlopen,但我不知道如何将cookies添加到请求中,而不是通过opener对象。
【解决方案2】:

根据文档,在 python 2.7.9 中添加了指定 CA 文件的功能,并且仅在 urlopen 调用中可用,如上一个答案中所述。

所以您确实需要将 opener.open() 更改为 urllib2.urlopen。 为了让它仍然使用开瓶器,请致电 urllib2.install_opener(opener) 在 urlopen 调用之前

这是我发现所有(cookies & login authentication & CA cert specified)的唯一方法

【讨论】: