-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcertificate_expired.py
executable file
·89 lines (65 loc) · 2.73 KB
/
certificate_expired.py
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
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import json
import requests
import socket
import ssl
import time
import os
def webhook(message, max_retries=3, retry_delay=3):
retries = 0
headers = {
"Content-Type": "application/json"
}
payload = json.dumps(message)
while retries < max_retries:
try:
response = requests.post(url, data=payload, headers=headers)
# 檢查請求是否成功,根據實際需求自行判斷
if response.status_code == 200:
print(response.text)
return None
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
retries += 1
# 等待指定的延遲時間
time.sleep(retry_delay)
return None
if __name__ == '__main__':
alert_days = 30
port = 443
server_list = open( "list.txt", "r")
url = os.getenv(URL)
for lists in server_list:
message = ""
# endpoint = lists.strip().split()[0]
domain = lists.strip().split()[0]
cdn = lists.strip().split()[1]
try:
# 連線到網站並獲取憑證
ctx = ssl.create_default_context()
with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s:
s.connect((domain, port))
cert = s.getpeercert()
# 解析憑證的有效期
cert_expiry_date = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
# 取得現在的日期和時間
now = datetime.datetime.now()
# 計算憑證的過期剩餘天數
remaining_days = (cert_expiry_date - now).days
if remaining_days < alert_days:
# message = "%s certificate %s will expires in %s days \n" % (cdn, domain, remaining_days)
message = {"msgtype": "text","text": {"content":"%s certificate %s will expires in %s days \n" % (cdn, domain, remaining_days)}}
# else:
# message = "The certificate for %s on %s is still valid for %s days" % (domain, cdn, remaining_days)
# message = {"msgtype": "text","text": {"content":"The certificate for %s on %s is still valid for %s days" % (domain, cdn, remaining_days)}}
print({"info": "The certificate for %s on %s is still valid for %s days" % (
domain, cdn, remaining_days)})
except ssl.SSLError as e:
print(f"An error occurred while checking the certificate: {e}")
except socket.error as e:
print(f"An error occurred while connecting to the domain: {e}")
# print(message)
if message:
webhook(message)