Python脚本自动检测SSL证书有效期与到期告警

听雨眠
听雨眠
发布时间:2026-10-13 | 4人浏览过
原创

本文提供基于Python的SSL证书有效期检测脚本。通过调用curl命令获取HTTPS响应头,利用正则表达式解析颁发时间、到期时间及颁发机构等关键信息,并计算剩余天数。结合邮件告警与页面展示功能,可实时监控大量域名的证书状态,防止因证书过期导致的服务中断。

Python SSL证书监控方案概述

将证书监控与邮件告警及页面展示功能相结合,即可实时掌握任意数量域名的SSL证书到期状态。

具体实现代码如下:

SSL证书检测核心代码实现


# coding: utf-8 
# 查询域名证书到期情况

import re
import time
import subprocess
from datetime import datetime
from io import StringIO

def main(domain):
  f = StringIO()
  comm = f"curl -Ivs https://{domain} --connect-timeout 10"

  result = subprocess.getstatusoutput(comm)
  f.write(result[1])

  m = re.search('start date: (.*?)\n.*?expire date: (.*?)\n.*?common name: (.*?)\n.*?issuer: CN=(.*?)\n', f.getvalue(), re.S)
  start_date = m.group(1)
  expire_date = m.group(2)
  common_name = m.group(3)
  issuer = m.group(4)

  # time 字符串转时间数组
  start_date = time.strptime(start_date, "%b %d %H:%M:%S %Y GMT")
  start_date_st = time.strftime("%Y-%m-%d %H:%M:%S", start_date)
  # datetime 字符串转时间数组
  expire_date = datetime.strptime(expire_date, "%b %d %H:%M:%S %Y GMT")
  expire_date_st = datetime.strftime(expire_date,"%Y-%m-%d %H:%M:%S")

  # 剩余天数
  remaining = (expire_date-datetime.now()).days

  print ('域名:', domain)
  print ('通用名:', common_name)
  print ('开始时间:', start_date_st)
  print ('到期时间:', expire_date_st)
  print (f'剩余时间: {remaining}天')
  print ('颁发机构:', issuer)
  print ('*'*30)

  time.sleep(0.5)

if __name__ == "__main__":
  domains = ['www.baidu.com'] 
  for domain in domains:
    main(domain)

检测结果示例分析

运行后的输出结果如下所示:

域名: www.baidu.com 通用名: baidu.com 开始时间: 2019-05-09 01:22:02 到期时间: 2020-06-25 05:31:02 剩余时间: 82天 颁发机构: GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE ******************************

以上内容即为本文的全部介绍,希望此方案能对各位的学习或工作带来帮助,同时也欢迎大家继续支持本站获取更多技术资源。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表