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

编程入门 行业动态 更新时间:2024-10-22 23:37:16

python脚本监听域名证书过期时间,<a href=https://www.elefans.com/category/jswz/34/1771306.html style=并将通知消息到钉钉"/>

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

版本一:

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

python3 ssl_spirtime.py --dingtalk-webhook =avd345324 --domains www.abc1 www.abc2 www.abc3

脚本如下

#!/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 =abdcsardaef--secret SEC75bcc2abdfd --domains www.abc1 www.abc2 www.abc3
#!/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": "=avbdcse345dd","secret": "SECaegdDEdaDSEGFdadd12334","domains": ["www.a.tel","www.b","www.c.app","www.d-cn","www.e","www.f","www.g","www.gg","www.sd","www.234","www.456","www.addf","www.advdwd","aqjs.aefdsdf","apap.adedgdg","cbap.asfew","ksjsw.adfewfd","wdxl.aeffadaf","wspr.afefd.shop","sktprd.daeafsdf.shop","webskt.afaefafa.shop","www.afaead","www.afewfsegs.co","www.aaeafsf","bdvt.aeraf.info","dl.afawef.co","dl.aefarge"]
}

脚本内容如下

#!/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 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 expires on 2024-03-03 00:00:00
Days remaining: 122 days
SSL certificate for www.aed expires on 2024-11-17 06:30:15
Days remaining: 381 days
SSL certificate for www.afedf expires on 2024-06-20 23:59:59
Days remaining: 232 days
SSL certificate for www.aefdfd expires on 2024-06-20 23:59:59

钉钉告警消息如下

更多推荐

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

本文发布于:2024-02-12 16:02:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1688469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并将   脚本   证书   消息   域名

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!