BASH

Automated SSL Certificate Expiration Check and Notification

Monitor SSL/TLS certificate expirations for your domains with Bash. This script checks certificate validity and sends email notifications if they are nearing expiry.

#!/bin/bash

# Configuration
DOMAIN="example.com"
PORT="443"
WARNING_DAYS=30 # Notify if certificate expires within this many days
RECIPIENT_EMAIL="[email protected]"

# Get certificate expiry date
EXPIRY_DATE_STR=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN":"$PORT" 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2)

# Check if expiry date was retrieved successfully
if [ -z "$EXPIRY_DATE_STR" ]; then
  echo "Error: Could not retrieve SSL certificate expiry date for $DOMAIN." >&2
  exit 1
fi

# Convert expiry date to Unix timestamp
EXPIRY_TIMESTAMP=$(date -d "$EXPIRY_DATE_STR" +%s)
CURRENT_TIMESTAMP=$(date +%s)

# Calculate days remaining until expiry
DAYS_REMAINING=$(( (EXPIRY_TIMESTAMP - CURRENT_TIMESTAMP) / (60*60*24) ))

echo "Certificate for $DOMAIN expires on: $EXPIRY_DATE_STR (Days remaining: $DAYS_REMAINING)"

# Send notification if certificate is nearing expiry
if [ "$DAYS_REMAINING" -le "$WARNING_DAYS" ]; then
  SUBJECT="SSL Certificate for $DOMAIN Expiring Soon!"
  MESSAGE="The SSL certificate for $DOMAIN expires in $DAYS_REMAINING days on $EXPIRY_DATE_STR. Please renew it."
  
  echo "Sending email notification to $RECIPIENT_EMAIL:"
  echo "Subject: $SUBJECT"
  echo "Message: $MESSAGE"

  # Use mail command to send email (ensure 'mailutils' or similar is installed)
  # echo "$MESSAGE" | mail -s "$SUBJECT" "$RECIPIENT_EMAIL"
  echo "Notification sent (mail command commented out for safety)."

else
  echo "Certificate for $DOMAIN is valid for more than $WARNING_DAYS days. No action needed."
fi

echo "Script finished."
How it works: This Bash script monitors SSL/TLS certificate expiration for a given domain. It uses `openssl s_client` to connect to the server and retrieve the certificate's end date, then parses this information. It calculates the remaining days until expiration and compares it against a configured warning threshold. If the certificate is nearing expiry, the script can send an email notification to a specified recipient, helping web administrators proactively renew certificates before they expire, preventing service interruptions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs