python脚本监听域名证书过期时间并通知消息到钉钉(最新推荐)

 更新时间:2023年11月03日 15:05:47   作者:yunson_Liu  
这篇文章主要介绍了python脚本监听域名证书过期时间并通知消息到钉钉(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

版本一:

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

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

脚本如下

#!/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、密钥和域名

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
#!/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执行脚本时指定配置文件

python3 ssl_spirtime.py --config-file config.json

config.json配置文件内容如下

{
    "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"
    ]
}

脚本内容如下

#!/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)

执行结果

/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

钉钉告警消息如下

到此这篇关于python脚本监听域名证书过期时间,并将通知消息到钉钉的文章就介绍到这了,更多相关python域名证书过期时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python爬取51job中hr的邮箱

    python爬取51job中hr的邮箱

    这篇文章主要为大家详细介绍了python爬取51job中hr的邮箱的相关资料,需要的朋友可以参考下
    2016-05-05
  • 详解Python自动化之文件自动化处理

    详解Python自动化之文件自动化处理

    今天给大家带来的是关于Python的相关知识,文章围绕着Python文件自动化处理展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • Python函数调用的几种方式(类里面,类之间,类外面)

    Python函数调用的几种方式(类里面,类之间,类外面)

    本文主要介绍了Python函数调用的几种方式(类里面,类之间,类外面),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • Pandas DataFrame如何按照一列数据的特定顺序进行排序

    Pandas DataFrame如何按照一列数据的特定顺序进行排序

    这篇文章主要介绍了Pandas DataFrame如何按照一列数据的特定顺序进行排序,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • 利用python编写一个图片主色转换的脚本

    利用python编写一个图片主色转换的脚本

    这篇文章主要给大家介绍了关于利用python编写一个图片主色转换脚本的相关资料,主要使用的是Python中的Pillow图像处理库,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起看看吧。
    2017-12-12
  • Python与机器学习库LightGBM使用详解

    Python与机器学习库LightGBM使用详解

    LightGBM是一种高效的梯度提升决策树框架,以其快速训练和高预测性能闻名,它通过直方图算法和基于叶子生长策略优化技术,能够在大规模数据集上提供卓越性能,本文详细介绍了如何使用LightGBM进行分类和回归任务,包括模型构建、参数调整
    2025-01-01
  • Django2.2配置xadmin的实现

    Django2.2配置xadmin的实现

    这篇文章主要介绍了Django2.2配置xadmin的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • Python使用openpyxl批量处理数据

    Python使用openpyxl批量处理数据

    openpyxl 是一个用于处理 xlsx 格式Excel表格文件的第三方python库,其支持Excel表格绝大多数基本操作。本文给大家介绍Python使用openpyxl批量处理数据的操作方法,感兴趣的朋友一起看看吧
    2021-06-06
  • Python中优雅处理JSON文件的方法实例

    Python中优雅处理JSON文件的方法实例

    JSON是一种轻量级的数据交换格式,JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯,这篇文章主要给大家介绍了关于Python中优雅处理JSON文件的相关资料,需要的朋友可以参考下
    2021-12-12
  • Python中语音转文字相关库介绍(最新推荐)

    Python中语音转文字相关库介绍(最新推荐)

    Python的speech_recognition库是一个用于语音识别的Python包,它可以使Python程序能够识别和翻译来自麦克风、音频文件或网络流的语音,这篇文章主要介绍了Python中语音转文字相关库介绍,需要的朋友可以参考下
    2023-05-05

最新评论