Check all SSL Certificates in a directory and report those that have expired or will expire soon (BASH)

These simple snippets iterates over certificates in a directory (you can change the find if you need to change how certs are discovered) and checks their expiry date using openssl.

The first snippet prints the filename of certs that have expired. The second prints the filename of certs which are currently valid but will expire within the next 14 days.

Details

  • Language: BASH

Snippet

# Certificates that have already expired
now=`date +'%s'`
for cert in `find ./ -type f`
do
    expiry=$(date --date="`openssl x509 -in $cert -noout -dates | grep -i "notAfter" | cut -d\= -f 2`" +'%s')

    if [ "$expiry" -lt "$now" ]
    then
        echo "$cert expired `openssl x509 -in $cert -noout -dates | grep -i "notAfter" | cut -d\= -f 2`"
    fi
done

# Certs expiring in the next 14 days
now=`date +'%s'`
then=`date --date="+14 days" +'%s'`
for cert in `find ./ -type f`
do
    expiry=$(date --date="`openssl x509 -in $cert -noout -dates | grep -i "notAfter" | cut -d\= -f 2`" +'%s')

    if [ "$expiry" -gt "$now" ] && [ "$expiry" -lt "$then" ]
    then
        echo "$cert will expire `openssl x509 -in $cert -noout -dates | grep -i "notAfter" | cut -d\= -f 2`"
    fi
done