"""
Test validity of certificates.
Tested on Ubuntu with Python 3.5 and python3-openssl package.
"""
import ssl
from datetime import datetime
from warnings import warn
import OpenSSL
def test_days_to_expiry(host='www.bluewin.ch', port=443):
cert = ssl.get_server_certificate((host, port))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
exp = x509.get_notAfter().decode('utf8') # Usually in format b'20200208104801Z'
if exp.endswith('Z'):
exp = exp[:-1]
then = datetime.strptime(exp, '%Y%m%d%H%M%S')
time_left = then - datetime.now()
# Test harness
assert time_left.days > 0
# Comfort functions
if time_left.days < 30:
serial = x509.get_serial_number()
warn('Certificate {} for {} expires in {} days.', serial, host, time_left.days)
return time_left.days