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 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.hqwc.cn/news/161531.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java配置47-Spring Eureka 未授权访问漏洞修复

文章目录 1. 背景2. 方法2.1 Eureka Server 添加安全组件2.2 Eureka Server 添加参数2.3 重启 Eureka Server2.4 Eureka Server 升级版本2.5 Eureka Client 配置2.6 Eureka Server 添加代码2.7 其他问题 1. 背景 项目组使用的 Spring Boot 比较老&#xff0c;是 1.5.4.RELEASE…

D-Link管理系统默认账号密码

默认口令为 admin:admin 登陆成功 文笔生疏&#xff0c;措辞浅薄&#xff0c;望各位大佬不吝赐教&#xff0c;万分感谢。 免责声明&#xff1a;由于传播或利用此文所提供的信息、技术或方法而造成的任何直接或间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c; 文章…

贝叶斯网络:利用变量消除(Variable Elimination)进行推理

贝叶斯网络简介 贝叶斯网络(Bayesian network)也叫贝氏网路、信念网络&#xff08;belief network&#xff09;或是有向无环图&#xff08;DAG&#xff09;模型&#xff0c;是一种概率图模型。它利用DAG的结构&#xff0c;得到一组随机变量{X1,X2,...,Xn}的条件概率分布&#…

matlab双目标定中基线物理长度获取

在MATLAB进行双目摄像机标定时,通常会获得相机的内参,其中包括像素单位的焦距(focal length)以及物理单位的基线长度(baseline)。对于应用中的深度估计和测量,基线长度的物理单位非常重要,因为它直接影响到深度信息的准确性。有时候,您可能只能获取像素单位的焦距和棋…

如何使用CodeceptJS、Playwright和GitHub Actions构建端到端测试流水线

介绍 端到端测试是软件开发的一个重要方面&#xff0c;因为它确保系统的所有组件都能正确运行。CodeceptJS是一个高效且强大的端到端自动化框架&#xff0c;与Playwright 结合使用时&#xff0c;它成为自动化Web、移动甚至桌面 (Electron.js) 应用程序比较好用的工具。 在本文中…

JavaScript的作用域和作用域链

作用域 ● 作用域&#xff08;Scoping&#xff09;&#xff1a;我们程序中变量的组织和访问方式。"变量存在在哪里&#xff1f;“或者"我们可以在哪里访问某个变量&#xff0c;以及在哪里不能访问&#xff1f;” ● 词法作用域&#xff08;Lexical scoping&#xff…

python创建一个简单的flask应用

下面用python在本地和服务器上分别创建一个简单的flask应用&#xff1a; 1.在pc本地 1&#xff09;pip flask后创建一个简单的脚本flask_demo.py from flask import Flaskapp Flask(__name__)app.route(/) def hello_world():return Hello, World!winR进入命令行&#xff0c;…

2.2整式的加减(第1课时)——合并同类项教学及作业设计

【学习目标】 1&#xff0e;理解同类项的概念&#xff0c;并能正确辨别同类项&#xff0e; 2&#xff0e;理解合并同类项的依据是乘法分配律&#xff0c;掌握合并同类项的方法&#xff0e; 知识点归纳&#xff1a; ★合并同类项后&#xff0c;所得的项的系数是___________…

Visual Studio使用Git忽略不想上传到远程仓库的文件

前言 作为一个.NET开发者而言&#xff0c;有着宇宙最强IDE&#xff1a;Visual Studio加持&#xff0c;让我们的开发效率得到了更好的提升。我们不需要担心环境变量的配置和其他代码管理工具&#xff0c;因为Visual Studio有着众多的拓展工具。废话不多说&#xff0c;直接进入正…

图数据库Neo4j——SpringBoot使用Neo4j 简单增删改查 复杂查询初步

前言 图形数据库是专门用于存储图形数据的数据库&#xff0c;它使用图形模型来存储数据&#xff0c;并且支持复杂的图形查询。常见的图形数据库有Neo4j、OrientDB等。 Neo4j是用Java实现的开源NoSQL图数据库&#xff0c;本篇博客介绍如何在SpringBoot中使用Neo4j图数据库&…

MySQL:事务

目录 概念事务特性开始事务事务的状态事务并发问题事务隔离级别 概念 MySQL事务是一组在数据库中执行的操作&#xff0c;它们必须要么全部成功执行&#xff0c;要么全部不执行。MySQL事务被设计为确保数据库中的数据的完整性和一致性&#xff0c;即使在并发访问的情况下也是如…

在Ubuntu上安装Redis并学习使用get、set和keys命令

目录 安装Redis切换到root用户搜索redis相关软件包安装redis修改配置文件重启服务器使用redis客户端连接服务器 get与set命令keys 安装Redis 我们在Ubuntu20.04上进行Redis的安装 切换到root用户 使用su命令&#xff1a; 在终端中&#xff0c;输入su并按回车键。然后输入roo…