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

这篇具有很好参考价值的文章主要介绍了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执行脚本时指定配置文件
python脚本监听域名证书过期时间,并将通知消息到钉钉,python,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文章来源地址https://www.toymoban.com/news/detail-738925.html

到了这里,关于python脚本监听域名证书过期时间,并将通知消息到钉钉的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Prometheus监控添加监控mongodb+docker+MySQL8.0+服务器系统进程监控+域名过期时间监控

    环境: 192.168.1.144  Ubuntu系统已经部署好Prometheus监控部署教程请看本人前面的教程  192.168.1.140  centos7系统已安装docker+docker-compose 1、在被监控端以docker-compose方式安装mongodb mkdir /data/mangodb/ #创建mangodb的目录 cd /data/mangodb/ #进入目录下 2,写docker-compose.yaml文件 vim docker-compose.y

    2024年02月02日
    浏览(54)
  • shell脚本之003获取固定时间段(分钟)内的日志,并将其定时通过sftp上传至服务器中

    #!/bin/bash export PATH=/home/ccbt/software/lftp-4.9.2/usr/local/bin/:$PATH # 获取当前系统时间 now=$(date +\\\"%Y/%m/%d %H:%M:%S\\\") echo \\\"当前日期时间:$now\\\" # 当前时间戳 now_time=$(date +%s) echo \\\"当前时间戳:$now_time\\\" #获取指定开始时间的时间戳 10分钟 time_befo=$(($now_time-600)) echo \\\"指定开始时间戳: $time_befo\\\"

    2024年02月01日
    浏览(57)
  • 防火墙规则过期通知

    作为规则管理最佳实践,大多数安全管理员为其防火墙规则设置到期日期。过期后,需要更正防火墙规则才能再次激活。但是,由于大多数组织都有数百个规则和多个安全管理员处理这些规则,因此几乎不可能查看过期的规则并手动纠正它们。这就是为什么拥有一个可以自动

    2024年02月16日
    浏览(34)
  • Python键盘监听:实现快捷操作和自动化脚本(监听组合键

    本文主要介绍一下使用Python进行事件监听功能,以实现一些特有的操作。本文旨在介绍如何实现这一功能。 笔者根据一些需求写了一个小工具,流程和功能如下图所示(实际功能有更多): 该工具主要实现了 键盘监听 和 鼠标连击; 通过键盘监听事件去驱动 鼠标做一些操作

    2024年02月13日
    浏览(40)
  • 使用Python和Twilio通过短信通知主持视频办公时间。

     当你想到“办公时间”时,你会想到什么?也许你会想象一位教授会留出时间让学生去他们的办公室寻求建议或接受指导。或者,你可以想象一位企业领导在日历上为同事和直接下属留出空间,让他们提问或分享想法。 随着虚拟和混合环境的兴起,许多人在网上办公,视频

    2023年04月15日
    浏览(48)
  • 【Python开发手册】JWT Token中添加过期时间和角色:简单易学的pyjwt

    💖 作者简介:大家好,我是Zeeland,全栈领域优质创作者。 📝 CSDN主页:Zeeland🔥 📣 我的博客:Zeeland 📚 Github主页: Undertone0809 (Zeeland) (github.com) 🎉 支持我:点赞👍+收藏⭐️+留言📝 📣 系列专栏:Python系列专栏 🍁 💬介绍:The mixture of software dev+Iot+ml+anything🔥 【cushy-s

    2023年04月23日
    浏览(46)
  • Redis,过期监听

    应用场景,优惠卷过期,监听 配置类 监听类

    2024年02月14日
    浏览(34)
  • 监听redis过期业务处理

    配置类: 过期监听类 

    2024年02月06日
    浏览(42)
  • SQLServer证书过期,重做证书

    (1)查询证书相关信息 SELECT * FROM sys.certificates 查看证书 SELECT * FROM sys.endpoints 查看端点 SELECT * FROM sys.syslogins 查看登录 SELECT * FROM sys.sysusers 查看用户 (2)删除可用性组 (3)删除端点 DROP ENDPOINT Hadr_endpoint (4)删除证书 DROP CERTIFICATE sqlserver_1_certificate DROP CERTIFICATE sqlserver_

    2024年02月07日
    浏览(37)
  • 使用Python的Requests和BeautifulSoup库来爬取新闻网站的新闻标题、发布时间、内容等信息,并将数据存储到数据库中

    BeautifulSoup是Python的一个HTML/XML解析库,用于从HTML或XML文件中提取数据。结合Python的requests库,可以实现网页爬取和数据提取。 以下是一个简单的使用BeautifulSoup和requests库实现爬虫的示例:   用requests库和BeautifulSoup4库,爬取校园新闻列表的时间、标题、链接、来源。

    2024年02月10日
    浏览(55)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包