排行榜
原创运维中心

python批量检查ssl过期时间并给企业微信发通知

本文阅读 1 分钟
首页 运维中心 正文
广告

检查域名ssl过期时间,请参考:python批量检查ssl过期时间

这里主要解决发送消息到企业微信内部群:

先贴目录结构:

check-ssl

├── domain-check-ssl.py

└── domain.txt


具体脚本逻辑:检查小于15天的域名

vim domain-check-ssl.py


#!/usr/bin/env python3
import ssl, socket
import requests
from dateutil import parser
import pytz
from datetime import datetime, timedelta
domain_expiration_list = []
requests.packages.urllib3.disable_warnings()
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context
def get_domain_content(domain):
    requests.packages.urllib3.disable_warnings()
    url = 'https://' + domain
    response = requests.get(url, verify=False).headers
    print(response)
def get_my_domain(mydomain):
    try:
        socket.setdefaulttimeout(5)
        my_addr = socket.getaddrinfo(mydomain, None)
        c = ssl.create_default_context()
        s = c.wrap_socket(socket.socket(), server_hostname=mydomain)
        s.connect((mydomain, 443))
        my_cert = s.getpeercert()
        get_my_cert_dated(mydomain, my_cert, my_addr)
    except ssl.CertificateError and socket.gaierror as e:
        pass
def get_my_cert_dated(domain, certs, my_addr):
    global domain_expiration_list
    cert_beginning_time = parser.parse(certs['notBefore']).astimezone(pytz.utc)
    cert_end_time = parser.parse(certs['notAfter']).astimezone(pytz.utc)
    print('域名:(%s)  证书失效时间: %s' % (domain, cert_end_time))
    current_utc_time = datetime.now(pytz.utc)
    time_difference = current_utc_time - cert_end_time
    is_more_than_5_days_in_future = time_difference.days < -15
    cert_end_time_str = cert_end_time.strftime('%Y-%m-%d')
    # 检查时间差是否大于 15 天
    if not is_more_than_5_days_in_future:
        print("给定的时间距离现在不超过15天")
        domain_expiration_list.append(
            {
                "keyname": domain,
                "value": cert_end_time_str,
            }
        )
def read_domain_files():
    global domain_expiration_list
    with open('/home/wwwroot/check-ssl/domain.txt', 'r',
              encoding="utf-8") as file:
        for domain in file:
            try:
                get_my_domain(domain.strip())
                #print('域名: (%s)' % (domain.strip()))
            except Exception as e:
                print('域名: (%s)-%s' % (domain.strip(), e))
    if len(domain_expiration_list) != 0:
        send_to_wx()
def send_to_wx():
    global domain_expiration_list
    wx_message = {
        "msgtype": "template_card",
        "template_card": {
            "card_type": "text_notice",
            "source": {
                "icon_url": "https://wework.qpic.cn/wwpic/252813_jOfDHtcISzuodLa_1629280209/0",
                "desc": "SSL时间检查脚本",
                "desc_color": 0
            },
            "main_title": {
                "title": "域名ssl检查通知",
            },
            "sub_title_text": "即将过期域名列表",
            "horizontal_content_list": domain_expiration_list,
            "card_action": {
                "type": 1,
                "url": "https://app.awesomepet.cn/admin/",
            }
        }
    }
    qx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx'# 这个是企业微信群机器人的消息通知地址
    requests.post(qx_url, json=wx_message)
if __name__ == "__main__":
    read_domain_files()


添加域名列表文件:

vim domain.txt


app.unfit.cn
store.unfit.cn
api.unfit.cn
cdn.unfit.cn
tools.unfit.cn


添加定时任务:

crontab -e
0 10 * * * /usr/local/bin/python3/bin/python3 /home/wwwroot/check-ssl/domain-check-ssl.py


原创文章,作者:大洋哥,如若转载,请注明出处:https://www.unfit.cn/archives/192.html
python脚本每10分钟自动执行阿里云dns解析
« 上一篇 02-26
广告