JRehkemper.de

Check SSL Expiration Date with Nagios

It can be really useful to monitor, if you need to exchange any ssl certificates.
Here is a short script which enables you to do that.

#!/bin/bash

# check if target was provided
if [ -z "$1" ]; then
	echo "no target provided"
	exit 1
fi

# set target port to second argument
TargetPort=$2
# check if a second argument was provided. if not set default port.
if [ -z "$2" ]; then
	TargetPort=443
fi

# openssl does not return so pipe the `echo -n` to close it once it finishes
# use openssl s_client to fetch the certificate from the target
# and use openssl x509 to extract the dates from the certificate.
# Then grep for the expiration date with `notAfter=` and remove "notAfter" from the output.
# You are left with the expiration date in a pretty formating.
ExpDatePretty=$(echo -n | openssl s_client -connect $1:$TargetPort 2> /dev/null | openssl x509 -text -noout -dates | grep notAfter= | sed 's/notAfter=//')

# convert the pretty timestamp to unix epoch timestamp
ExpDateEpoch=$(date --date="$ExpDatePretty" +%s)

# get the current date as unix epoch timestamp
CurDateEpoch=$(date +%s)

# get the difference in seconds between current date and expiration date
RemainingSeconds=$(($ExpDateEpoch-$CurDateEpoch))
RemainingDays=$(($RemainingSeconds/60/60/24))

echo "$RemainingDays days remaining."

# Less then 10 days, return status WARNING
if [[ $RemainingDays -lt 10 ]]; then
        exit 2
# Less than 30 days, return status CRITICAL
elif [[ $RemainingDays -lt 30 ]]; then
        exit 1
# Return status OK
else
        exit 0
fi

To use it, we need to create a command and a service. This can be done in any config file in your nagios-configuration-directory.

define command {
    command_name    check_cert_valid_time
    command_line    $USER1$/check_cert_valid_time.sh $ARG1$ $ARG2$
}

define service {
        service_description     Expire Certificate nagios-01.home
        use                     local-service
        host_name               nagios-01.home
        check_command           check_cert_valid_time!nagios-01.home!443
}

Last we need to reload nagios, to load the new configuration changes.

$ systemctl reload nagios

Now you have certificate check for the host nagios-01.home. Of course you will need to adjust this name to your hostname.

profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.