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

news/2024/12/22 23:05:29/

版本一:

执行脚本带上 --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 requestsdef 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 certificatenot_after = cert['notAfter']# Convert the date string to a datetime objectexpiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')return expiration_datedef 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).daysprint(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 timedef 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 certificatenot_after = cert['notAfter']# Convert the date string to a datetime objectexpiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')return expiration_datedef send_dingtalk_message(webhook_url, secret, message):headers = {'Content-Type': 'application/json'}# Get the current timestamp in millisecondstimestamp = str(int(round(time.time() * 1000)))# Combine timestamp and secret to create a sign stringsign_string = f"{timestamp}\n{secret}"# Calculate the HMAC-SHA256 signaturesign = base64.b64encode(hmac.new(secret.encode(), sign_string.encode(), hashlib.sha256).digest()).decode()# Create the payload with the calculated signaturepayload = {"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).daysprint(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 jsondef 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 certificatenot_after = cert['notAfter']# Convert the date string to a datetime objectexpiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')return expiration_datedef send_dingtalk_message(webhook_url, secret, message):headers = {'Content-Type': 'application/json'}# Get the current timestamp in millisecondstimestamp = str(int(round(time.time() * 1000)))# Combine timestamp and secret to create a sign stringsign_string = f"{timestamp}\n{secret}"# Calculate the HMAC-SHA256 signaturesign = base64.b64encode(hmac.new(secret.encode(), sign_string.encode(), hashlib.sha256).digest()).decode()# Create the payload with the calculated signaturepayload = {"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).daysprint(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

钉钉告警消息如下
在这里插入图片描述


http://www.ppmy.cn/news/1190740.html

相关文章

第三届字节跳动奖学金官宣开奖,13位优秀科研学子每人获10万奖学金

最近&#xff0c;第三届字节跳动奖学金正式公布了获奖者名单。 经过字节跳动技术专家团队层层评审&#xff0c;本届字节跳动奖学金共有来自北京大学、复旦大学、清华大学、上海交通大学、香港科技大学、浙江大学、中国科学技术大学&#xff08;按拼音首字母排序&#xff09;的 …

UG NX机械设计软件常见安装问题

UG软件版本这里咱们就不提了&#xff0c;大部分伙伴应该都是钩子激活软件&#xff0c;肯定会遇到或多或少的安装问题&#xff0c;今天这里给大家总结了下&#xff0c;需要的小伙伴自取。 有其他问题可以一起讨论&#xff0c;也希望看到的小伙伴多关注支持哦。 安装UGNX的必要…

TypeScript之高级类型

一、是什么 除了string、number、boolean 这种基础类型外&#xff0c;在 typescript 类型声明中还存在一些高级的类型应用 这些高级类型&#xff0c;是typescript为了保证语言的灵活性&#xff0c;所使用的一些语言特性。这些特性有助于我们应对复杂多变的开发场景 二、有哪…

Python的web自动化学习(三)Selenium的显性、隐形等待

引言&#xff1a; WebDriver的显性等待和隐形等待是用于在测试过程中等待元素加载或操作完成的两种等待方式。了解此两种方式是为后面自动化找到适合的方法去运用 显性等待&#xff08;Explicit Wait&#xff09; 显性等待是通过使用WebDriverWait类和ExpectedConditions类来…

JavaEE就业课 V12.5 完整版

简介 众所周知&#xff0c;在IT互联网领域是靠技术吃饭的&#xff0c;更符合企业需求的先进技术才是硬通货。黑马Java学科一直在行动&#xff0c;一直走在行业最前沿! 四项目制用四个不同类型、不同开发深度的项目&#xff0c;去解决企业用人需求与学员具备相应开发能力匹配的…

Android NDK开发详解之调试和性能分析的系统跟踪概览

Android NDK开发详解之调试和性能分析的系统跟踪概览 系统跟踪指南 “系统跟踪”就是记录短时间内的设备活动。系统跟踪会生成跟踪文件&#xff0c;该文件可用于生成系统报告。此报告有助于您了解如何最有效地提升应用或游戏的性能。 有关进行跟踪和性能分析的全面介绍&#x…

【数据结构】树形结构所有路径复原为链表

目录 1. 树形结构可视化 2. 树形结构转为链表 此目标是要还原树形结构的所有路径。树形结构是一种常见的数据结构&#xff0c;它表示元素之间层次关系。在树形结构中&#xff0c;每个节点可能拥有一个或多个子节点&#xff0c;形成了一个分层的结构。为了还原树形结构的路径&…

Ubuntu定时执行任务

cron一个Linux定时执行工具&#xff0c;可以定时执行一些任务。 crontab -l 如果显示“no crontab for xxx” 说明没有启动cron。 service cron start 这样就启动cron了。 服务相关命令&#xff1a; service cron stop service cron restart service cron reload 查看当…