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

查看:98
本文介绍了使用 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 证书,所以即使证书无效,Python 库如 urllib2 和 Twisted 也会很乐意使用该证书.

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.HTTPS 连接

这个类现在默认执行所有必要的证书和主机名检查.要恢复到之前未验证的行为,可以将 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() 传递给上下文参数.

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.

请注意,新的内置验证基于系统提供的证书数据库.与此相反,requests 包提供了自己的证书包.两种方法的优缺点在信任数据库部分讨论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天全站免登陆