BASH

Check SSL Certificate Expiry and Send Notification

Monitor the expiration date of an SSL certificate for a given domain and send a notification if it's nearing expiry, preventing service interruptions.

#!/bin/bash

DOMAIN="yourdomain.com"
DAYS_THRESHOLD=30 # Notify if expiry is within this many days
NOTIFICATION_EMAIL="[email protected]"

EXPIRY_DATE=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN":443 2>/dev/null | openssl x509 -noout -enddate | cut -d'=' -f2)

if [ -z "$EXPIRY_DATE" ]; then
  echo "Error: Could not retrieve SSL certificate expiry for $DOMAIN."
  exit 1
fi

EXPIRY_EPOCH=$(date -d "$EXPIRY_DATE" +%s)
CURRENT_EPOCH=$(date +%s)

SECONDS_LEFT=$((EXPIRY_EPOCH - CURRENT_EPOCH))
DAYS_LEFT=$((SECONDS_LEFT / 86400))

if [ "$DAYS_LEFT" -le "$DAYS_THRESHOLD" ]; then
  SUBJECT="SSL Certificate for $DOMAIN Expiring Soon ($DAYS_LEFT days left)"
  MESSAGE="The SSL certificate for $DOMAIN will expire on $EXPIRY_DATE. Only $DAYS_LEFT days remaining.
Please renew it promptly."

  echo "$MESSAGE" | mail -s "$SUBJECT" "$NOTIFICATION_EMAIL"
  echo "Notification sent: $SUBJECT"
else
  echo "SSL Certificate for $DOMAIN is valid. $DAYS_LEFT days remaining."
fi
How it works: This script checks the SSL certificate expiration date for a specified domain using `openssl`. It calculates the remaining days and, if the expiry is within a configurable threshold, it sends an email notification to alert the administrator, helping to prevent unexpected certificate-related downtime. Ensure `mail` (or `sendmail`) is configured on your system.

Need help integrating this into your project?

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

Hire DigitalCodeLabs