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实现GIF动图加载和降帧的方法详解

    Python实现GIF动图加载和降帧的方法详解

    这篇文章主要为大家详细介绍了如何利用Python和Pygame实现GIF动图加载和降帧的效果,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2023-02-02
  • Python中的命令行参数解析工具之docopt详解

    Python中的命令行参数解析工具之docopt详解

    docopt 是一个用来解析命令行参数的工具,当想要在 Python 程序后面附加参数时,就不需要再为此而发愁了。下面这篇文章主要介绍了Python中命令行参数解析工具之docopt的相关资料,介绍的非常详细,需要的朋友们下面来一起看看吧。
    2017-03-03
  • Python图像运算之图像锐化和边缘检测

    Python图像运算之图像锐化和边缘检测

    这篇文章主要和大家讲解一下常见的图像锐化和边缘检测方法,即Roberts算子和Prewitt算子。文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-12-12
  • Python四大金刚之列表详解

    Python四大金刚之列表详解

    这篇文章主要介绍了Python的列表,小编觉得这篇文章写的还不错,需要的朋友可以参考下,希望能够给你带来帮助
    2021-10-10
  • Python中集合的内置函数详解

    Python中集合的内置函数详解

    这篇文章主要介绍了Python中集合的内置函数详解,集合在python里面是另外一种对象,它的特征是在大括号里面,并且各个元素是唯一的,今天我们来看一下其内置了哪些函数,需要的朋友可以参考下
    2023-08-08
  • 带你详细了解Python GUI编程框架

    带你详细了解Python GUI编程框架

    今天小编就为大家分享一篇python 实现GUI(图形用户界面)编程详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-08-08
  • Python Thread虚假唤醒概念与防范详解

    Python Thread虚假唤醒概念与防范详解

    这篇文章主要介绍了Python Thread虚假唤醒概念与防范,虚假唤醒是一种现象,它只会出现在多线程环境中,指的是在多线程环境下,多个线程等待在同一个条件上,等到条件满足时,所有等待的线程都被唤醒,但由于多个线程执行的顺序不同
    2023-02-02
  • python实现给字典添加条目的方法

    python实现给字典添加条目的方法

    这篇文章主要介绍了python实现给字典添加条目的方法,是比较实用的字典操作技巧,实例备有简单的注释,需要的朋友可以参考下
    2014-09-09
  • Pandas DataFrame操作数据增删查改

    Pandas DataFrame操作数据增删查改

    我们在用 pandas 处理数据的时候,经常会遇到用其中一列数据替换另一列数据的场景。这一类的需求估计很多人都遇到,当然还有其它更复杂的。解决这类需求的办法有很多,这里我们来推荐几个,这篇文章主要介绍了Pandas DataFrame操作数据的增删查改
    2022-10-10
  • 基于python 字符编码的理解

    基于python 字符编码的理解

    下面小编就为大家带来一篇基于python 字符编码的理解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09

最新评论