Skip to content

Instantly share code, notes, and snippets.

Created August 29, 2018 22:10
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
ssl check
import socket
import ssl
import datetime
from multiprocessing.dummy import Pool as ThreadPool
# Tuples containing host and port
CERTS_TO_CHECK = [("host_one", 443),
("host_two", 25)]
class AlreadyExpired(Exception):
def ssl_expiry_datetime(target):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
hostname, port = target
cont = ssl.create_default_context()
cont.verify_mode = ssl.CERT_REQUIRED
if port != 25:
conn = cont.wrap_socket(
# Don't wait forever!
conn.connect((hostname, port))
ssl_info = conn.getpeercert()
import smtplib
s = smtplib.SMTP(host=hostname)
ssl_info = s.sock.getpeercert(binary_form=False)
# parse the string from the certificate into a Python datetime object
return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
def ssl_valid_time_remaining(hostname):
"""Get the number of days left in a cert's lifetime."""
expires = ssl_expiry_datetime(hostname)
return expires - datetime.datetime.utcnow()
def ssl_expires_in(hostname, buffer_days=14):
"""Check if `hostname` SSL cert expires is within `buffer_days`.
Raises `AlreadyExpired` if the cert is past due
remaining = ssl_valid_time_remaining(hostname)
# if the cert expires in less than two weeks, we should reissue it
if remaining < datetime.timedelta(days=0):
# cert has already expired - uhoh!
raise AlreadyExpired("Cert expired %s days ago" % remaining.days)
elif remaining < datetime.timedelta(days=buffer_days):
# expires sooner than the buffer
print("{} on port {} expiring in {} days".format(hostname[0], hostname[1], remaining.days))
pool = ThreadPool(4), CERTS_TO_CHECK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment