如何让python httplib接受不受信任的证书?

2024-05-19 05:53:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何让python httplib接受不受信任的证书?我在我的web服务器上创建了一个snake oil/自签名证书,而python客户端无法连接,因为我正在使用一个不受信任的证书

我宁愿在我的客户端代码中解决这个问题,而不是让它信任我的系统。

import httplib


def main():
    conn = httplib.HTTPSConnection("127.0.0.1:443")
    conn.request("HEAD","/")
    res = conn.getresponse()
    print res.status, res.reason
    data = res.read()
    print len(data)


if __name__ == "__main__":
    main()

Tags: 代码服务器web客户端datamain系统res
2条回答

在检查Python2.7.14源代码时,可以设置一个环境变量

PYTHONHTTPSVERIFY=0

这将导致证书验证在默认情况下被禁用(这将适用于来自您的程序的所有请求)。

我相信这是从2.7.12+开始的,但不适用于3.x

参考号PEP 493: Verify HTTPS by default, but allow envvar to override that

我的一些脚本在更新计算机后停止工作。结果,这就是问题所在:https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection

Changed in version 2.7.9: context was added.

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

因此,如果您的Python版本是>;=2.7.9(在我的例子中是2.7.10),您可能会遇到这种情况。为了解决这个问题,我更新了我的电话:

httplib.HTTPSConnection(hostname, timeout=5, context=ssl._create_unverified_context())

这可能是保持相同行为的最简单的更改。

相关问题 更多 >

    热门问题