用Python来检查域名HTTPS证书
最近有个需求需要检查管理域名证书是否过期, 需要连到各个域名然后下载证书检查时间, 网上找了一通, 找到了目前来说比较方便的代码..
python">import ssl, sockethostname = \'www.qq.com\'
c = ssl.create_default_context()
s = c.wrap_socket(socket.socket(), server_hostname=hostname)
s.connect((hostname, 443))
cert = s.getpeercert()
cert 里面就是证书的详细信息了, 如下图所示.
拿到这些信息后, 与当前时间进行对比, 就可以了.
在比较旧的系统上, 有可能出现 certificate verify failed: unable to get local issuer certificate
这种报错
初步处理办法:
- 更新系统的ca证书
yum update ca-certificates
- 重新编译openssl
- 重新编译Python3
如果这种办法也无法解决这个报错的话, 还有另一种方式进行检查
需要提前安装pip3 install pyOpenSSL
关键代码如下:
import sslimport time
import OpenSSL
hostname = \'www.qq.com\'
port = 443
cert = ssl.get_server_certificate((hostname, port)).encode()
cert_obj = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
cert_time = int(time.strftime(\'%s\', time.strptime(cert_obj.get_notAfter().decode(), \'%Y%m%d%H%M%SZ\')))
这样也是能获取到启用了SSL功能服务端口的证书信息的.
以上是 用Python来检查域名HTTPS证书 的全部内容, 来源链接: utcz.com/z/388506.html