使用Python验证SSL证书 [英] Validate SSL certificates with Python

查看:326
本文介绍了使用Python验证SSL证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个脚本,通过HTTPS连接到公司内部网上的一堆站点,并验证他们的SSL证书是否有效;他们没有过期,他们是为正确的地址等发行的。我们为这些网站使用我们自己的内部公司证书颁发机构,因此我们有CA的公钥来验证证书。

I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.

默认情况下,Python在使用HTTPS时接受并使用SSL证书,因此即使证书无效,诸如urllib2和Twisted之类的Python库也会很乐意使用证书。

Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.

是否有一个好的库可以让我通过HTTPS连接到网站并以这种方式验证其证书?

如何在Python中验证证书?

How do I verify a certificate in Python?

推荐答案

从发布版本2.7.9 / 3.4.3开始,Python 默认情况下尝试执行证书验证。

From release version 2.7.9/3.4.3 on, Python by default attempts to perform certificate validation.

这已在PEP 467中提出,值得一读:https://www.python.org/dev/peps/pep-0476/

This has been proposed in PEP 467, which is worth a read: https://www.python.org/dev/peps/pep-0476/

这些更改会影响所有相关的stdlib模块(urllib / urllib2,http,httplib)。

The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).

相关文档:

https://docs.python.org/2/library /httplib.html#httplib.HTTPSConnection


此类现在默认执行所有必要的证书和主机名检查。要恢复到之前未经验证的行为,可以将ssl._create_unverified_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.

https://docs.python.org/3/library/http.client.html#http.client .HTTPSConnection


版本3.4.3中更改:此类现在默认执行所有必要的证书和主机名检查。要恢复到之前的未经验证的行为,可以将ssl._create_unverified_context()传递给context参数。

Changed in version 3.4.3: 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.

请注意新建的-in验证基于系统提供的证书数据库。与此相反,请求包附带了自己的证书包。 Trust数据库部分讨论了这两种方法的优缺点。 PEP 476

Note that the new built-in verification is based on the system-provided certificate database. Opposed to that, the requests package ships its own certificate bundle. Pros and cons of both approaches are discussed in the Trust database section of PEP 476.

这篇关于使用Python验证SSL证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆