Skip to content

Instantly share code, notes, and snippets.

@twirrim
Created August 29, 2018 22:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twirrim/5634973bb2f6b912c1de9bea151411d6 to your computer and use it in GitHub Desktop.
Save twirrim/5634973bb2f6b912c1de9bea151411d6 to your computer and use it in GitHub Desktop.
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):
pass
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(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# Don't wait forever!
conn.settimeout(3.0)
conn.connect((hostname, port))
ssl_info = conn.getpeercert()
conn.close()
else:
import smtplib
s = smtplib.SMTP(host=hostname)
s.connect()
s.starttls(context=cont)
ssl_info = s.sock.getpeercert(binary_form=False)
s.close()
# 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)
pool.map(ssl_expires_in, CERTS_TO_CHECK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment