Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash SSL Certificate Expiration Check
#!/bin/bash
TARGET="mysite.example.net";
RECIPIENT="hostmaster@mysite.example.net";
DAYS=7;
echo "checking if $TARGET expires in less than $DAYS days";
expirationdate=$(date -d "$(: | openssl s_client -connect $TARGET:443 -servername $TARGET 2>/dev/null \
| openssl x509 -text \
| grep 'Not After' \
|awk '{print $4,$5,$7}')" '+%s');
in7days=$(($(date +%s) + (86400*$DAYS)));
if [ $in7days -gt $expirationdate ]; then
echo "KO - Certificate for $TARGET expires in less than $DAYS days, on $(date -d @$expirationdate '+%Y-%m-%d')" \
| mail -s "Certificate expiration warning for $TARGET" $RECIPIENT ;
else
echo "OK - Certificate expires on $expirationdate";
fi;
@opthakur

This comment has been minimized.

Copy link

opthakur commented Jul 15, 2020

How to add multiple targets ?
@cgmartin

@Clanwarz

This comment has been minimized.

Copy link

Clanwarz commented Jul 23, 2020

@opthakur

Place all your domains in a file. Run the script in a loop, giving the loop a domain each time it runs. Maybe something like this:

#!/bin/bash

DOMAINS="/path/to/list/of/domains/list.txt"
RECIPIENT="hostmaster@mysite.example.net"
DAYS="7"

while read -r TARGET; do
  echo "checking if $TARGET expires in less than $DAYS days";
  expirationdate=$(date -d "$(: | openssl s_client -connect "$TARGET":443 -servername "$TARGET" 2>/dev/null \
                                | openssl x509 -text \
                                | grep 'Not After' \
                                |awk '{print $4,$5,$7}')" '+%s');
  in7days=$(($(date +%s) + (86400*DAYS)));
  if [ "$in7days" -gt "$expirationdate" ]; then
      echo "KO - Certificate for $TARGET expires in less than $DAYS days, on $(date -d @"$expirationdate" '+%Y-%m-%d')" \
      | mail -s "Certificate expiration warning for $TARGET" $RECIPIENT ;
  else
      echo "OK - Certificate expires on $expirationdate";
  fi;
done<"${DOMAINS}"

Define your list of domains on line 3. I added some double quotes to his original script.

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.