Certificate expiry monitored from outside

A check that reads the certificate file on disk confirms the file is valid. It says nothing about what the server is actually serving, which may be a different file, an old one, or the default nginx certificate because a reload failed.

#!/bin/sh
end=$(echo | openssl s_client -connect "$1:443" -servername "$1" 2>/dev/null 
      | openssl x509 -noout -enddate | cut -d= -f2)
days=$(( ($(date -d "$end" +%s) - $(date +%s)) / 86400 ))

[ "$days" -lt 21 ] && { echo "CRITICAL: $1 expires in $days days"; exit 2; }
exit 0

Twenty-one days is the useful threshold when renewal starts at thirty: by then two weeks of automated attempts have failed and there is still a week to fix it by hand. Run it from a machine that is not the web server, and check every hostname rather than one — the certificate that expires is always the one on the staging box nobody was watching.