Last active
March 27, 2025 20:49
-
-
Save petarov/62db34bc31a6600b5d88c3487ec27f7d to your computer and use it in GitHub Desktop.
Let's Encrypt Certificate Expiry Push Notification via ntfy.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
MAIN_DIR="/etc/letsencrypt/live" | |
THRESHOLD_DAYS=7 | |
EXPIRY_LOG="/tmp/cert_expiry.log" # Log file to track expiry dates | |
ALERT_URL="ntfy.sh/<your-topic>" | |
touch "$EXPIRY_LOG" | |
# Function to check expiry and send alert | |
check_certificate() { | |
local cert_path="$1" | |
local cert_name="$(basename $(dirname $cert_path))" | |
# Extract expiry date using OpenSSL | |
local cert_expiry_raw | |
cert_expiry_raw=$(openssl x509 -in "$cert_path" -noout -enddate | cut -d= -f2) | |
# Convert expiry date to timestamp | |
local cert_expiry_ts | |
cert_expiry_ts=$(date -d "$cert_expiry_raw" +%s) | |
# Get current timestamp | |
local now_ts | |
now_ts=$(date +%s) | |
# Calculate days until expiry | |
local days_until_expiry | |
days_until_expiry=$(( (cert_expiry_ts - now_ts) / 86400 )) | |
# Extract relative path for logging | |
local cert_dir | |
cert_dir=$(dirname "$cert_path") | |
# Read last saved expiry from log | |
local last_expiry | |
last_expiry=$(grep "^$cert_dir:" "$EXPIRY_LOG" | awk -F ':' '{print substr($0, index($0,$2))}') | |
# If expiry is below threshold and changed, trigger alert | |
if [[ $days_until_expiry -le $THRESHOLD_DAYS ]]; then | |
echo "Warn: Certificate at $cert_path expires in $days_until_expiry days" | |
if [[ "$last_expiry" != "$cert_expiry_raw" ]]; then | |
curl -d "$cert_name expires in $days_until_expiry days" $ALERT_URL | |
# Update log | |
sed -i "\|^$cert_dir:|d" "$EXPIRY_LOG" | |
echo "$cert_dir:$cert_expiry_raw" >> "$EXPIRY_LOG" | |
else | |
echo "Info: Certificate expiry meesage already sent: $cert_name" | |
fi | |
else | |
echo "Info: Certificate not yet expired: $cert_name" | |
fi | |
} | |
find "$MAIN_DIR" -name "cert.pem" | while read -r cert; do | |
check_certificate "$cert" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment