编写Python脚本在证书过期10天内将域名信息发送到钉钉

1、配置文件config.json

bash 复制代码
{
    "dingtalk-webhook": "https://oapi.dingtalk.com/robot/send?access_token=XXXXXXXXXXXXXX",
    "secret": "XXXXXXXXXXXXXXXXXXXXXX",
    "domains": [
        "www.advd.tel",
        "dre.dfefer.cn:8443"
    ]
}

2、Python脚本正文

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

def get_ssl_cert_expiration(domain, port=443):
    try:
        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
    except Exception as e:
        raise RuntimeError(f"Error retrieving SSL certificate for {domain} on port {port}: {str(e)}")

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}")

def parse_domain_and_port(domain_with_port):
    if ':' in domain_with_port:
        domain, port = domain_with_port.split(':')
        return domain, int(port)
    else:
        return domain_with_port, 443  # 默认使用443端口

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_with_port in domains:
        domain, port = parse_domain_and_port(domain_with_port)

        try:
            expiration_date = get_ssl_cert_expiration(domain, port)
            current_date = datetime.now()
            days_remaining = (expiration_date - current_date).days

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

            if days_remaining < 10:
                message = f"SSL certificate for {domain} (port {port}) will expire on {expiration_date}. Only {days_remaining} days remaining."
                send_dingtalk_message(dingtalk_webhook, secret, message)
        except Exception as e:
            error_message = f"Failed to retrieve SSL certificate for {domain} (port {port}). Error: {str(e)}"
            print(error_message)
            send_dingtalk_message(dingtalk_webhook, secret, error_message)

3、执行命令

bash 复制代码
/usr/bin/python3 /root/ssl/ssl_spirtime_check.py --config-file /root/ssl/config.json
相关推荐
禁默2 分钟前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Cachel wood9 分钟前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
Code哈哈笑11 分钟前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
終不似少年遊*14 分钟前
pyecharts
python·信息可视化·数据分析·学习笔记·pyecharts·使用技巧
程序猿进阶15 分钟前
深入解析 Spring WebFlux:原理与应用
java·开发语言·后端·spring·面试·架构·springboot
Python之栈16 分钟前
【无标题】
数据库·python·mysql
qq_4336184417 分钟前
shell 编程(二)
开发语言·bash·shell
charlie11451419132 分钟前
C++ STL CookBook
开发语言·c++·stl·c++20
袁袁袁袁满32 分钟前
100天精通Python(爬虫篇)——第113天:‌爬虫基础模块之urllib详细教程大全
开发语言·爬虫·python·网络爬虫·爬虫实战·urllib·urllib模块教程
ELI_He99938 分钟前
PHP中替换某个包或某个类
开发语言·php