我如何让python httplib接受不受信任的证书? [英] How do I have python httplib accept untrusted certs?
问题描述
我如何让python httplib接受不受信任的证书?我在网络服务器上创建了一个蛇油/自签名证书,并且python客户端无法连接,因为我使用的是不受信任的证书.
How do I have python httplib accept untrusted certs? I created a snake oil/self signed cert on my webserver, and my python client fails to connect as I am using a untrusted cert.
我宁愿在客户端代码中解决该问题,也不希望它在我的系统上得到信任.
I'd rather problematically fix this in my client code rather than have it trusted on my system.
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()
推荐答案
更新计算机后,我的某些脚本停止工作.原来,这就是问题所在: https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection
Some of my scripts stopped working after updating my computer. Turns out, this was the problem: https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection
在2.7.9版中进行了更改:添加了上下文.
Changed in version 2.7.9: context was added.
此类现在默认情况下执行所有必要的证书和主机名检查.要恢复为先前未验证的行为,可以将ssl._create_unverified_context()传递给context参数.
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.1),您可能会遇到此问题.为了解决这个问题,我更新了通话:
So if your version of Python is >= 2.7.9 (2.7.10 in my case), you'll likely run into this. To fix it, I updated my call:
httplib.HTTPSConnection(hostname, timeout=5, context=ssl._create_unverified_context())
这可能是保留相同行为的最简单的更改.
This is likely the simplest change to retain the same behavior.
这篇关于我如何让python httplib接受不受信任的证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!