others linux服务器运维 django3 监控 k8s golang 数据库 大数据 前端 devops 理论基础 java oracle 运维日志

域名证书过期时间监控

访问量:1643 创建时间:2022-12-06

python脚本1

公司域名比较多,好几百个,在用shell脚本监控时问题较多(参考https://www.cnblogs.com/dgshubo/p/16870864.html)

# -*- coding: utf-8 -*-

"""
1. 此脚本为检测域名的SSL证书过期时间,距离当前时间还有多久。
2. 此脚本需要配合 config.py 使用,config.py 里面是以列表的形式写入需要检测的域名。
"""

import socket
import ssl
import datetime
import time
#import config
import logging


def get_domain_cert(domain):
        socket.setdefaulttimeout(5)

        cxt = ssl.create_default_context()
        skt = cxt.wrap_socket(socket.socket(),server_hostname=domain)

        skt.connect((domain,443))
        cert = skt.getpeercert()

        # 获取证书结束的GMT时间
        end_time = cert["notAfter"]

        # 关闭socket连接
        skt.close()

        # 返回证书过期时间,返回的是GMT时间
        return end_time


def get_end_time(end_time,domain):
        # 将证书到期时间转换常规可读的时间,还是GMT时间
        GMT_FORMAT = '%b %d %H:%M:%S %Y GMT'
        GMT_TIME = datetime.datetime.strptime(end_time, GMT_FORMAT)
        # 将证书到期转换成东 8 区的时间
        East_8th_District = GMT_TIME + datetime.timedelta(hours=8)
        print("域名:%s 的证书到期时间:%s" %(domain,East_8th_District))

        # 将结束时间转换成时间戳,预备以后做计算,小于多少天报警。
        end_time_stamp = time.mktime(East_8th_District.timetuple())
        now_time_stamp = time.time()

        # 算出证书过期的天数
        time_difference = end_time_stamp - now_time_stamp
        # 将时间戳转换成天数
        days = ("%.2f" % (time_difference / 60 / 60 / 24))
        return days

if __name__ == '__main__':
        server_list = ['www.baidu.com','abc.com']
        print("检测时间:%s" % time.strftime('%Y-%m-%d %H:%M:%S'))
        for i in server_list:
                try:
                        end_time = get_domain_cert(i)
                except:
                        logging.error("请检查域名:%s 是否正确。 该域名否使用SSL证书,或者域名填写错误。\n" % i)
                else:
                        days = get_end_time(end_time, i)
                        print("域名:%s 的证书过期离当前时间还有:%s 天。\n" %(i, days))
[root@jkweb ssl]# python3 a.py 
检测时间:2022-12-06 10:56:32
域名:www.baidu.com 的证书到期时间:2023-08-06 13:16:01
域名:www.baidu.com 的证书过期离当前时间还有:243.10 天。

ERROR:root:请检查域名:3msas.com 是否正确。 该域名否使用SSL证书,或者域名填写错误。

脚本2

已经过期的证书,或者无效证书也可以采集到时间。需要python3 ,urllib3

from urllib3.contrib import pyopenssl
import datetime
def get_expire(https_url):
    try:
        conn = pyopenssl.ssl.create_connection((https_url, 443),timeout=5)
        sock = pyopenssl.ssl.SSLContext(pyopenssl.ssl.PROTOCOL_SSLv23).wrap_socket(conn, server_hostname=https_url)
        cert = pyopenssl.ssl.DER_cert_to_PEM_cert(sock.getpeercert(True))
        data = pyopenssl.OpenSSL.crypto.load_certificate(pyopenssl.OpenSSL.crypto.FILETYPE_PEM, cert)
        print(data.get_notAfter().decode()[0:-1])
        expire_time = datetime.datetime.strptime(data.get_notAfter().decode()[0:-1], '%Y%m%d%H%M%S')
        expire_days = (expire_time - datetime.datetime.now()).days
        return True, {"expire_time": str(expire_time), "expire_days": expire_days}
    except Exception as e:
        print(e)
        return False, {}
#is_suc, ssl_expire_dict = get_expire("www.baidu.com")
is_suc, ssl_expire_dict = get_expire("www.baidu.com")
print(is_suc) 
print(ssl_expire_dict) 

可视化Domain Admin

Domain Admin可视化管理域名证书到期 项目地址:https://github.com/mouday/domain-admin

运行环境:Python 3.7.0

登陆评论: 使用GITHUB登陆