Skip to content

Instantly share code, notes, and snippets.

@dnorhoj
Created December 20, 2023 16:31
Show Gist options
  • Save dnorhoj/af7b30868f1d51004c9eda76aa55ec27 to your computer and use it in GitHub Desktop.
Save dnorhoj/af7b30868f1d51004c9eda76aa55ec27 to your computer and use it in GitHub Desktop.
check_x509_certificate_expiry.sh
#!/bin/bash
# Daniel Norhøj <daniel@dnorhoj.me>
# This script checks all x.509 certificates in the specified directory
# and prints the expiration date of each certificate.
# Usage: ./check_certificates.sh /path/to/certificates
# The script expects the certificates to be in PEM format.
# The script expects the certificates to be named like this:
# <hostname>/cert.pem
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
for cert in $(find $1 -name cert.pem); do
# Get hostname from certificate path
hostname=$(echo $cert | rev | cut -d/ -f 2 | rev)
echo -en "$hostname:\n - "
exipry=$(openssl x509 -enddate -noout -in $cert | cut -d= -f2-)
# Convert expiration date to unix timestamp
exipry_unix=$(date -d "$exipry" +%s)
# Get current unix timestamp
now_unix=$(date +%s)
# Calculate difference in seconds
diff=$(($exipry_unix - $now_unix))
# Convert difference to days
days=$(($diff / 86400))
# Print expiration date
if [ $days -lt 0 ]; then
echo -e "${RED}Expired $((-days)) days ago${NC}"
elif [ $days -lt 30 ]; then
echo -e "${YELLOW}Expires in $days days${NC}"
elif [ $days ]; then
echo -e "${GREEN}Expires in $days days${NC}"
fi
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment