first commit
This commit is contained in:
87
ssl_check_final.py
Normal file
87
ssl_check_final.py
Normal file
@ -0,0 +1,87 @@
|
||||
import ssl
|
||||
import socket
|
||||
from datetime import datetime
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
|
||||
HOSTS = [
|
||||
("google.com", 443),
|
||||
("example.org", 443),
|
||||
("erebor.cbpio.pl", 443),
|
||||
]
|
||||
|
||||
SMTP_SERVER = 'smtp.gmail.com'
|
||||
SMTP_PORT = 587
|
||||
EMAIL_FROM = 'example@mail.com'
|
||||
EMAIL_PASSWORD = 'password'
|
||||
EMAIL_TO = 'example1@mail.com'
|
||||
EMAIL_SUBJECT = 'Daily SSL Certificate Report'
|
||||
|
||||
def get_cert_expiry(host, port):
|
||||
try:
|
||||
context = ssl.create_default_context()
|
||||
with socket.create_connection((host, port), timeout=5) as sock:
|
||||
with context.wrap_socket(sock, server_hostname=host) as ssock:
|
||||
cert = ssock.getpeercert()
|
||||
expiry_str = cert['notAfter']
|
||||
expiry_date = datetime.strptime(expiry_str, '%b %d %H:%M:%S %Y %Z')
|
||||
return expiry_date
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def status_by_days(days_left):
|
||||
if days_left > 14:
|
||||
return 'OK'
|
||||
elif days_left > 5:
|
||||
return 'WARNING'
|
||||
elif days_left >= 0:
|
||||
return 'CRITICAL'
|
||||
else:
|
||||
return 'CRITICAL (EXPIRED)'
|
||||
|
||||
def main():
|
||||
report_lines = [f'Subject: {EMAIL_SUBJECT}', '', 'SSL Certificate Expiration Report:', '']
|
||||
now = datetime.utcnow()
|
||||
|
||||
for host, port in HOSTS:
|
||||
expiry_date = get_cert_expiry(host, port)
|
||||
host_port = f'{host}:{port}'
|
||||
|
||||
if expiry_date is None:
|
||||
report_lines.append(f'Host: {host_port}')
|
||||
report_lines.append('Expires: N/A')
|
||||
report_lines.append('Days left: N/A')
|
||||
report_lines.append('Status: ERROR')
|
||||
report_lines.append('')
|
||||
continue
|
||||
|
||||
days_left = (expiry_date - now).days
|
||||
status = status_by_days(days_left)
|
||||
|
||||
expiry_str = expiry_date.strftime('%Y-%m-%d')
|
||||
report_lines.append(f'Host: {host_port}')
|
||||
report_lines.append(f'Expires: {expiry_str}')
|
||||
report_lines.append(f'Days left: {days_left}')
|
||||
report_lines.append(f'Status: {status}')
|
||||
report_lines.append('')
|
||||
|
||||
report = '\n'.join(report_lines)
|
||||
|
||||
with open('/home/username/projectname/data/INFO/mail.txt', 'w') as f:
|
||||
f.write(report)
|
||||
|
||||
msg = EmailMessage()
|
||||
msg.set_content(report)
|
||||
msg['Subject'] = EMAIL_SUBJECT
|
||||
msg['From'] = EMAIL_FROM
|
||||
msg['To'] = EMAIL_TO
|
||||
|
||||
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
|
||||
server.starttls()
|
||||
server.login(EMAIL_FROM, EMAIL_PASSWORD)
|
||||
server.send_message(msg)
|
||||
print("Raport zostal wyslany e-mailem.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
Reference in New Issue
Block a user