0%

Checking SSL certificate expiry dates with Python

I recently needed a script to inspect the SSL certificate expiry dates of several company websites so that we could replace certificates before they expired.

This post records one simple way to do that in Python.

An easy approach is to use the OpenSSL library to parse the certificate and read its expiry time:

1
pip install pyOpenSSL

Then the script can look like this:

1
2
3
4
5
6
7
8
import ssl
import OpenSSL

def get_ssl_expiry_date(host, port=443):
""" get notAfter data from server cert """
cert = ssl.get_server_certificate((host, port))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
return x509.get_notAfter().decode()

The returned expiry time looks like this:

1
'20220219235959Z'

That is a UTC timestamp string. If needed, you can convert it into a local timezone with another small helper:

1
2
3
4
5
6
7
8
9
10
11
12
13
import datetime
from pytz import timezone

# conf
SRC_TZ = 'UTC'
DST_TZ = 'Asia/Shanghai'

def load_ssl_date(dt_string, pattern='%Y%m%d%H%M%SZ'):
""" convert ssl date from string to datetime obj """
src_tz = timezone(SRC_TZ)
dst_tz = timezone(DST_TZ)
dt = src_tz.localize(datetime.datetime.strptime(dt_string, pattern))
return dt.astimezone(tz=dst_tz)

After that, it is straightforward to check whether a certificate is close to expiring.

I also came across a very useful site while testing this:

https://badssl.com

It provides many kinds of intentionally broken SSL scenarios. For example:

https://expired.badssl.com/

That makes it handy when testing how your code behaves around expired certificates and other SSL edge cases.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?