Thursday, June 11, 2020

Linux script to email when pem certificate will expire

#!/bin/sh

########################################################
#
#       Check certificates inside a pem formatted file
#
########################################################

# files=($(find /directory -mindepth 1 -maxdepth 1 -name '*.crt'))
declare -a files=("/directory/server.crt" "/directory/server2.crt")

# 30 days in seconds
days=30
limit=$(($days * 24 * 60 * 60))

echo "Checking pem files for certificate(s) expired in less than $days days."

# current time in seconds since epoch
now=$(date "+%s")

# for each file we want to check
for pem in "${files[@]}"; do
   # They expire at this time in seconds since epoch
   enddate=$(openssl x509 -enddate -noout -in "$pem")
   expires_at=$(date -d "$(: | echo $enddate |cut -d= -f 2)" +%s)
   # the difference
   expires_in=$((expires_at - now))
   expires_days=$(($expires_in / 86400))
   # if the certificate will expire in less than limit
   if (( expires_in < limit )); then
      echo "[WARNING] Certificate $pem expires on '$enddate' ($expires_days day(s) remaining)."
      printf "Automated message from server $HOSTNAME:\n[WARNING] Certificate $pem expires on '$enddate' ($expires_days day(s) remaining)." | curl --url 'smtp://smtpserver.com' --mail-from 'me@mail.com' --mail-rcpt 'support_team@mail.com'
   else
      echo "[OK] Certificate $pem expires on '$enddate' ($expires_days day(s) remaining)."
   fi
done

No comments: