1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| #!/usr/bin/env python3 # -*- coding: utf-8 -*-
import ssl, socket import requests from dateutil import parser import pytz import datetime import telegram
expire_domain_list = [] day_list = [] # 告警函数,填写你小飞机bot的token和指定组id def telegram_alarm(message): bot = telegram.Bot(token='1645507005:AAFSOD8kx_-SylYr3SDFHdiiCosMmdEPVQA') bot.send_message(chat_id=-52222222222, text=message)
def parse(time_str): """ Parse time format. :param time_str: <str> time string :return: <datetime.date> date """ # 使用split()函数将字符串转化为列表,并分解出年月日 time_list = time_str.split("-") year = time_list[0] month = time_list[1] day = time_list[2] # 将日期转换为datetime.date格式并返回 return datetime.date(int(year), int(month), int(day))
def get_my_domain(mydomain): try: c = ssl.create_default_context() s = c.wrap_socket(socket.socket(), server_hostname=mydomain) s.connect((mydomain, 443)) my_cert = s.getpeercert() get_my_cert_dated(mydomain, my_cert) except ssl.CertificateError and socket.gaierror as e: pass
def get_my_cert_dated(domain, certs): cert_end_time = parser.parse(certs['notAfter']).astimezone(pytz.utc) aaa = str(cert_end_time).split()[0] f = datetime.datetime.now() s = datetime.datetime.strftime(f, "%Y-%m-%d") global Days Days = (parse(aaa)-parse(s)).days print(domain,Days) # 告警阈值,证书小于10天就触发告警 if Days < 10: expire_domain_list.append(domain) day_list.append(Days)
# 域名存放文件,/python/domain.list。把需要监控的域名写进文件里,如: baidu.com|x5.qq.com def read_domain_files(): with open('/python/domain.list', 'r', encoding="utf-8") as file: for domain in file: try: get_my_domain(domain.strip()) except: pass
if __name__ == "__main__": read_domain_files()
format_info = '' for i in expire_domain_list[:10]: format_info = format_info + i + '\n'
if len(expire_domain_list) < 10 and len(expire_domain_list) > 0: telegram_alarm(message='即将过期的api域名有(小于{}天): {}'.format(min(day_list), format_info))
elif len(expire_domain_list) > 10: telegram_alarm(message='即将过期的api域名有(小于{}天): {}'.format(min(day_list), format_info)) telegram_alarm(message='默认只显示10条, 剩余{}个要过期域名存放在"/tmp/expire_api.log"文件里.'.format(len(expire_domain_list[10:]))) expire_api_file=open('/tmp/expire_api.log', 'w') for i in expire_domain_list[10:]: expire_api_file.write(i+'\n')
|