python脚本监听域名证书过期时间,并将通知消息到钉钉

版本一:

执行脚本带上 --dingtalk-webhook和--domains后指定钉钉token和域名

handlebars 复制代码
python3 ssl_spirtime.py --dingtalk-webhook https://oapi.dingtalk.com/robot/send?access_token=avd345324 --domains www.abc1.com www.abc2.com www.abc3.com

脚本如下

python 复制代码
#!/usr/bin/python3
import ssl
import socket
from datetime import datetime
import argparse
import requests

def get_ssl_cert_expiration(domain, port=443):
    context = ssl.create_default_context()
    conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=domain)
    conn.connect((domain, port))
    cert = conn.getpeercert()
    conn.close()

    # Extract the expiration date from the certificate
    not_after = cert['notAfter']

    # Convert the date string to a datetime object
    expiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')

    return expiration_date

def send_dingtalk_message(webhook_url, message):
    headers = {'Content-Type': 'application/json'}
    payload = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    
    response = requests.post(webhook_url, json=payload, headers=headers)
    
    if response.status_code == 200:
        print("Message sent successfully to DingTalk")
    else:
        print(f"Failed to send message to DingTalk. HTTP Status Code: {response.status_code}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Test SSL certificate expiration for multiple domains")
    parser.add_argument("--dingtalk-webhook", required=True, help="DingTalk webhook URL")
    parser.add_argument("--domains", nargs='+', required=True, help="List of domains to test SSL certificate expiration")

    args = parser.parse_args()

    for domain in args.domains:
        expiration_date = get_ssl_cert_expiration(domain)
        current_date = datetime.now()
        days_remaining = (expiration_date - current_date).days

        print(f"SSL certificate for {domain} expires on {expiration_date}")
        print(f"Days remaining: {days_remaining} days")

        if days_remaining < 300:
            message = f"SSL certificate for {domain} will expire on {expiration_date}. Only {days_remaining} days remaining."
            send_dingtalk_message(args.dingtalk_webhook, message)

版本二

执行脚本带上 --dingtalk-webhook、--secret和--domains后指定钉钉token、密钥和域名

handlebars 复制代码
python3 ssl_spirtime4.py --dingtalk-webhook https://oapi.dingtalk.com/robot/send?access_token=abdcsardaef--secret SEC75bcc2abdfd --domains www.abc1.com www.abc2.com www.abc3.com
python 复制代码
#!/usr/bin/python3
import ssl
import socket
from datetime import datetime
import argparse
import requests
import hashlib
import hmac
import base64
import time

def get_ssl_cert_expiration(domain, port=443):
    context = ssl.create_default_context()
    conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=domain)
    conn.connect((domain, port))
    cert = conn.getpeercert()
    conn.close()

    # Extract the expiration date from the certificate
    not_after = cert['notAfter']

    # Convert the date string to a datetime object
    expiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')

    return expiration_date

def send_dingtalk_message(webhook_url, secret, message):
    headers = {'Content-Type': 'application/json'}

    # Get the current timestamp in milliseconds
    timestamp = str(int(round(time.time() * 1000)))

    # Combine timestamp and secret to create a sign string
    sign_string = f"{timestamp}\n{secret}"
    
    # Calculate the HMAC-SHA256 signature
    sign = base64.b64encode(hmac.new(secret.encode(), sign_string.encode(), hashlib.sha256).digest()).decode()

    # Create the payload with the calculated signature
    payload = {
        "msgtype": "text",
        "text": {
            "content": message
        },
        "timestamp": timestamp,
        "sign": sign
    }
    
    response = requests.post(f"{webhook_url}&timestamp={timestamp}&sign={sign}", json=payload, headers=headers)
    
    if response.status_code == 200:
        print("Message sent successfully to DingTalk")
    else:
        print(f"Failed to send message to DingTalk. HTTP Status Code: {response.status_code}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Test SSL certificate expiration for multiple domains")
    parser.add_argument("--dingtalk-webhook", required=True, help="DingTalk webhook URL")
    parser.add_argument("--secret", required=True, help="DingTalk robot secret")
    parser.add_argument("--domains", nargs='+', required=True, help="List of domains to test SSL certificate expiration")

    args = parser.parse_args()

    for domain in args.domains:
        expiration_date = get_ssl_cert_expiration(domain)
        current_date = datetime.now()
        days_remaining = (expiration_date - current_date).days

        print(f"SSL certificate for {domain} expires on {expiration_date}")
        print(f"Days remaining: {days_remaining} days")

        if days_remaining < 10:
            message = f"SSL certificate for {domain} will expire on {expiration_date}. Only {days_remaining} days remaining."
            send_dingtalk_message(args.dingtalk_webhook, args.secret, message)

终极版本

python执行脚本时指定配置文件

handlebars 复制代码
python3 ssl_spirtime.py --config-file config.json

config.json配置文件内容如下

handlebars 复制代码
{
    "dingtalk-webhook": "https://oapi.dingtalk.com/robot/send?access_token=avbdcse345dd",
    "secret": "SECaegdDEdaDSEGFdadd12334",
    "domains": [
        "www.a.tel",
        "www.b.com",
        "www.c.app",
        "www.d-cn.com",
        "www.e.com",
        "www.f.com",
        "www.g.com",
        "www.gg.com",
        "www.sd.com",
        "www.234.com",
        "www.456.com",
        "www.addf.com",
        "www.advdwd.com",
        "aqjs.aefdsdf.com",
        "apap.adedgdg.com",
        "cbap.asfew.com",
        "ksjsw.adfewfd.cn",
        "wdxl.aeffadaf.com",
        "wspr.afefd.shop",
        "sktprd.daeafsdf.shop",
        "webskt.afaefafa.shop",
        "www.afaead.cn",
        "www.afewfsegs.co",
        "www.aaeafsf.com",
        "bdvt.aeraf.info",
        "dl.afawef.co",
        "dl.aefarge.com"
    ]
}

脚本内容如下

python 复制代码
#!/usr/bin/python3
import ssl
import socket
from datetime import datetime
import argparse
import requests
import hashlib
import hmac
import base64
import time
import json

def get_ssl_cert_expiration(domain, port=443):
    context = ssl.create_default_context()
    conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=domain)
    conn.connect((domain, port))
    cert = conn.getpeercert()
    conn.close()

    # Extract the expiration date from the certificate
    not_after = cert['notAfter']

    # Convert the date string to a datetime object
    expiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')

    return expiration_date

def send_dingtalk_message(webhook_url, secret, message):
    headers = {'Content-Type': 'application/json'}

    # Get the current timestamp in milliseconds
    timestamp = str(int(round(time.time() * 1000)))

    # Combine timestamp and secret to create a sign string
    sign_string = f"{timestamp}\n{secret}"
    
    # Calculate the HMAC-SHA256 signature
    sign = base64.b64encode(hmac.new(secret.encode(), sign_string.encode(), hashlib.sha256).digest()).decode()

    # Create the payload with the calculated signature
    payload = {
        "msgtype": "text",
        "text": {
            "content": message
        },
        "timestamp": timestamp,
        "sign": sign
    }
    
    response = requests.post(f"{webhook_url}&timestamp={timestamp}&sign={sign}", json=payload, headers=headers)
    
    if response.status_code == 200:
        print("Message sent successfully to DingTalk")
    else:
        print(f"Failed to send message to DingTalk. HTTP Status Code: {response.status_code}")

if __name__ == "__main__":
    # 从配置文件中加载配置
    with open("config.json", 'r') as config_file:
        config = json.load(config_file)

    dingtalk_webhook = config.get("dingtalk-webhook")
    secret = config.get("secret")
    domains = config.get("domains")

    for domain in domains:
        expiration_date = get_ssl_cert_expiration(domain)
        current_date = datetime.now()
        days_remaining = (expiration_date - current_date).days

        print(f"SSL certificate for {domain} expires on {expiration_date}")
        print(f"Days remaining: {days_remaining} days")

        if days_remaining < 10:
            message = f"SSL certificate for {domain} will expire on {expiration_date}. Only {days_remaining} days remaining."
            send_dingtalk_message(dingtalk_webhook, secret, message)

执行结果

handlebars 复制代码
/usr/bin/python3 /root/ssl_spirtime.py --config-file /root/config.json
SSL certificate for www.a.tel expires on 2024-06-08 23:59:59
Days remaining: 220 days
SSL certificate for www.b.com expires on 2024-05-23 07:45:13
Days remaining: 203 days
SSL certificate for www.c.app expires on 2024-05-23 07:45:13
Days remaining: 203 days
SSL certificate for www.d-cn.com expires on 2024-03-03 00:00:00
Days remaining: 122 days
SSL certificate for www.aed.com expires on 2024-11-17 06:30:15
Days remaining: 381 days
SSL certificate for www.afedf.com expires on 2024-06-20 23:59:59
Days remaining: 232 days
SSL certificate for www.aefdfd.com expires on 2024-06-20 23:59:59

钉钉告警消息如下

相关推荐
aini_lovee1 小时前
python在容器内克隆拉取git私有仓库
git·python·elasticsearch
安全系统学习3 小时前
网络安全之RCE简单分析
开发语言·python·算法·安全·web安全
蹦蹦跳跳真可爱5894 小时前
Python----神经网络发(神经网络发展历程)
人工智能·python·深度学习·神经网络·计算机视觉
chao_7894 小时前
标注工具核心代码解析——class AnnotationVie【canvas.py]
开发语言·python·qt5
struggle20255 小时前
tvm开源程序是适用于 CPU、GPU 和专用加速器的开放式深度学习编译器堆栈
人工智能·python·深度学习
仟濹6 小时前
「pandas 与 numpy」数据分析与处理全流程【数据分析全栈攻略:爬虫+处理+可视化+报告】
大数据·python·数据分析·numpy·pandas
测试杂货铺6 小时前
postman接口测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
四川兔兔6 小时前
pytorch 之 nn 库与调试
人工智能·pytorch·python
終不似少年遊*6 小时前
机器学习方法实现数独矩阵识别器
人工智能·python·opencv·机器学习·计算机视觉·矩阵
程序员的世界你不懂7 小时前
Appium+python自动化(二十一)- Monkey指令操作手机
python·appium·自动化