Check URLs list and send an email if their SSL is expiring in Python

Code:

import datetime
import smtplib
from urllib.parse import urlparse
from urllib.request import urlopen
from ssl import SSLContext, HAS_TLSv1_3

exp_date = datetime.datetime.today() + datetime.timedelta(days=30)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('youremail@gmail.com', 'password')

urls = ['https://www.google.com', 'https://www.facebook.com']

for url in urls:
    parsed = urlparse(url)
    hostname = parsed.hostname
    ctx = SSLContext(TLSv1_3_METHOD if HAS_TLSv1_3 else TLSv1_2_METHOD)
    ssl_info = ctx.cache.get_server_certificate(addr=(hostname, 443))
    cert_exp_date = datetime.datetime.strptime(ssl_info['notAfter'], '%b %d %H:%M:%S %Y %Z')
    if cert_exp_date < exp_date:
        message = "The SSL certificate for {} is expiring soon.".format(hostname)
        server.sendmail('youremail@gmail.com', 'recipient@gmail.com', message)
server.quit()

Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *