Bash script: check when your SSL certificates expire, for a whole list of hosts

Certificates renew themselves until the day they do not. This checks any number of hosts and tells you how many days each certificate has left. Needs only openssl, timeout and GNU date, so it runs on any Linux box as it is.

#!/usr/bin/env bash
# cert_check.sh - days left on TLS certificates
# usage: ./cert_check.sh host[:port] ...     or     ./cert_check.sh hosts.txt
set -u

WARN_DAYS="${WARN_DAYS:-14}"
rc=0

check() {
  local target="$1" host port end days
  host="${target%%:*}"
  port="${target##*:}"
  [ "$port" = "$target" ] && port=443

  end=$(echo | timeout 10 openssl s_client -connect "$host:$port" -servername "$host" 2>/dev/null \
        | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)

  if [ -z "$end" ]; then
    printf 'FAIL  %-34s could not read a certificate\n' "$host:$port"
    rc=2
    return
  fi

  days=$(( ( $(date -d "$end" +%s) - $(date +%s) ) / 86400 ))

  if [ "$days" -lt 0 ]; then
    printf 'DEAD  %-34s expired %s days ago\n' "$host:$port" "$(( -days ))"
    rc=2
  elif [ "$days" -lt "$WARN_DAYS" ]; then
    printf 'WARN  %-34s %s days left\n' "$host:$port" "$days"
    [ "$rc" -lt 1 ] && rc=1
  else
    printf 'OK    %-34s %s days left\n' "$host:$port" "$days"
  fi
}

if [ "$#" -eq 0 ]; then
  echo "usage: $0 host[:port] ... | file" >&2
  exit 64
fi

for arg in "$@"; do
  if [ -f "$arg" ]; then
    while read -r line; do
      line="${line%%#*}"
      line="${line// /}"
      [ -n "$line" ] && check "$line"
    done < "$arg"
  else
    check "$arg"
  fi
done

exit "$rc"

Using it

./cert_check.sh example.com mail.example.com:465
./cert_check.sh hosts.txt
WARN_DAYS=30 ./cert_check.sh hosts.txt

hosts.txt is one host per line, # starts a comment.

The exit code is 0 when everything is fine, 1 when something is inside the warning window and 2 when a certificate is expired or could not be read. That makes it easy to hang on cron:

0 8 * * * /opt/scripts/cert_check.sh /opt/scripts/hosts.txt | grep -v '^OK' | mail -E -s "certificates" you@example.com

A few details

-servername sends the host name in the handshake. Leave it out and a server with several sites hands you the default certificate, which is usually the wrong one.

It reads the certificate the server presents. It does not verify the chain, so a certificate from the wrong authority still shows as OK with days left. For expiry watching that is what you want. It is not a full TLS test.

Port 25 and 587 with STARTTLS need -starttls smtp added to the s_client call. I left it out to keep the script short. Ports that speak TLS from the first byte (443, 465, 993) work as written.