编写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
相关推荐
Theodore_10222 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
网易独家音乐人Mike Zhou2 小时前
【卡尔曼滤波】数据预测Prediction观测器的理论推导及应用 C语言、Python实现(Kalman Filter)
c语言·python·单片机·物联网·算法·嵌入式·iot
安静读书2 小时前
Python解析视频FPS(帧率)、分辨率信息
python·opencv·音视频
----云烟----4 小时前
QT中QString类的各种使用
开发语言·qt
lsx2024064 小时前
SQL SELECT 语句:基础与进阶应用
开发语言
小二·4 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic4 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
向宇it4 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
武子康4 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
转世成为计算机大神5 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式