#!/usr/bin/env python3
import ssl, socket
import requests
from dateutil import parser
import pytz
import time
from DingDingBot.DDBOT import DingDing
dd = DingDing(webhook="XXXX") #想换成企微的话就把webhook换成企微的
requests.packages.urllib3.disable_warnings()
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
def get_domain_content(domain):
requests.packages.urllib3.disable_warnings()
url = 'https://' + domain
response = requests.get(url, verify=False).headers
print(response)
def get_my_domain(mydomain):
try:
socket.setdefaulttimeout(5)
my_addr = socket.getaddrinfo(mydomain, None)
c = ssl.create_default_context()
s = c.wrap_socket(socket.socket(), server_hostname=mydomain)
s.connect((mydomain, 443))
my_cert = s.getpeercert()
return get_my_cert_dated(mydomain, my_cert, my_addr)
except (ssl.CertificateError, socket.gaierror) as e:
return None, None, None
def get_my_cert_dated(domain, certs, my_addr):
cert_beginning_time = parser.parse(certs['notBefore']).astimezone(pytz.utc)
cert_end_time = parser.parse(certs['notAfter']).astimezone(pytz.utc)
s = str(cert_end_time) #证书失效时间转为str
v = s[:-6] #证书失效时间去掉后面6个字符
b = (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) #系统当前时间
timetoday = time.strptime(b, "%Y-%m-%d %H:%M:%S") #系统当前时间转换为时间戳
timefuture = time.strptime(v, "%Y-%m-%d %H:%M:%S") #证书失效时间转换为时间戳
timeStamp1 = int(time.mktime(timetoday)) #系统当前时间戳转换为int
timeStamp2 = int(time.mktime(timefuture)) #证书失效时间转换为int
a = (timeStamp2 - timeStamp1) #时间戳差值
h = a / 86400 #时间戳转换为天数
if h <= 30: #当天数小于30天时返回域名和剩余天数
return domain, int(h)
return None, None
def read_domain_files():
expiring_domains = []
with open('./domain.txt', 'r', encoding="utf-8") as file:
for domain in file:
try:
domain = domain.strip()
expiring_domain, remaining_days = get_my_domain(domain)
if expiring_domain:
expiring_domains.append((expiring_domain, remaining_days))
except Exception as e:
print('域名: (%s)-%s' % (domain.strip(), e))
return expiring_domains
def save_to_file(expiring_domains):
with open('./expiring_domains.txt', 'w', encoding='utf-8') as f:
for domain, remaining_days in expiring_domains:
f.write(f'{domain}: 剩余 {remaining_days} 天\n')
if __name__ == "__main__":
expiring_domains = read_domain_files()
save_to_file(expiring_domains)
if expiring_domains:
dd.Send_Text_Msg(Content='以下域名的证书即将过期:\n' + '\n'.join([f'{domain}: 剩余 {remaining_days} 天' for domain, remaining_days in expiring_domains]))
什么?!这竟然是ssl证书检测过期时间并发送webhook通知的脚本?
于 2024-05-22 09:32:55 首次发布