Manually checking certificate expiration dates across multiple servers is tedious and prone to human error. Shell scripts come to the rescue, automating the process and providing an efficient way to stay ahead of potential security issues. Let’s learn how to build a shell script for this purpose.
Prerequisites
- OpenSSL: Most systems will have OpenSSL pre-installed.
- Basic Shell Scripting Knowledge: Familiarity with loops, variables, and conditional statements is needed.
- List of Servers: A text file containing the hostnames or IP addresses of the servers to check.
Sample Shell Script
Bash
#!/bin/bash
# Path to your server list
SERVER_LIST="/path/to/your/server_list.txt"
# Loop through the list of servers
while read SERVER; do
echo "------ Checking expiration for $SERVER ------"
# Extract the expiration date with OpenSSL
EXPIRATION_DATE=$(openssl s_client -servername $SERVER -connect $SERVER:443 2>/dev/null </dev/null |\
openssl x509 -noout -enddate | sed -e 's#notAfter=##')
# Convert the expiration date into Epoch time for comparison
EXPIRATION_SECONDS=$(date -d "$EXPIRATION_DATE" +%s)
CURRENT_SECONDS=$(date +%s)
DAYS_TO_EXPIRE=$(( (EXPIRATION_SECONDS - CURRENT_SECONDS) / 86400 ))
# Set a warning threshold
WARNING_THRESHOLD=30
# Output and alerts
if [ $DAYS_TO_EXPIRE -lt 0 ]; then
echo " EXPIRED! Please renew the certificate."
elif [ $DAYS_TO_EXPIRE -le $WARNING_THRESHOLD ]; then
echo " WARNING: Certificate expires in $DAYS_TO_EXPIRE days."
else
echo " Certificate is valid."
fi
done < $SERVER_LIST
Explanation
- Shebang (
#!/bin/bash
): Indicates the script should be executed with the Bash interpreter. - Variables: Stores the server list path and a warning threshold for expiring certificates.
- Loop: Iterates over each server in your
server_list.txt
file. - OpenSSL Commands: Extracts the certificate’s expiration date information.
- Date Conversion: Converts the expiration date to Unix Epoch time (seconds since January 1st, 1970) for easy calculations.
- Calculating Days Remaining: Determines the number of days until the certificate expires.
- Conditional Output: Provides status messages, indicating expired or soon-to-expire certificates.
How to Use the Script
- Modify Variables: Edit the
SERVER_LIST
andWARNING_THRESHOLD
variables to match your setup. - Server List: Create a file (e.g.,
server_list.txt
) with one server hostname or IP address per line. - Execute: Make the script executable (
chmod +x check_certificates.sh
) and run it (./check_certificates.sh
).
Enhancements
- Email Notifications: Integrate email sending (e.g., using the
mail
command) to receive alerts. - Customizable Thresholds: Allow the warning threshold to be passed in as a command-line argument.
- Logging: Record the results in a log file for auditing.
Read also: