Operations 7 min read

Automated SSL Certificate Expiration Monitoring via SSH with Python

This guide explains how to prepare the environment, install required Python libraries, and use a complete script that connects to a remote server via SSH to check SSL certificate expiration dates and send email alerts when certificates are near expiry.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Automated SSL Certificate Expiration Monitoring via SSH with Python

Environment Preparation

Install the required Python libraries: paramiko for SSH connections, requests for HTTP requests, and smtplib for sending emails. You can install them with the following command:

pip install paramiko requests

Sample Code

The following is a complete Python script that performs the certificate check and sends an email alert:

import paramiko
import requests
from datetime import datetime, timedelta
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# Configuration parameters
SERVER_URL = "https://www.example.com"  # replace with your server URL
WARNING_THRESHOLD_DAYS = 30  # days before expiration to trigger warning
EMAIL_HOST = "smtp.example.com"  # SMTP server address
EMAIL_PORT = 587  # SMTP server port
EMAIL_USERNAME = "[email protected]"  # sender email address
EMAIL_PASSWORD = "your_email_password"  # sender email password
RECIPIENT_EMAIL = "[email protected]"  # recipient email address
# SSH configuration
SSH_HOST = "ssh.example.com"  # SSH server address
SSH_PORT = 22  # SSH port
SSH_USERNAME = "your_ssh_username"  # SSH username
SSH_PASSWORD = "your_ssh_password"  # SSH password
def get_certificate_expiration(url):
"""Retrieve the HTTPS certificate expiration date."""
response = requests.get(url, verify=True)
cert = response.connection.sock.getpeercert()
expiration_date = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")
return expiration_date
def send_email(subject, body):
"""Send an email notification."""
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = EMAIL_USERNAME
msg['To'] = RECIPIENT_EMAIL
msg['Subject'] = Header(subject, 'utf-8')
try:
smtp_obj = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
smtp_obj.starttls()  # enable TLS encryption
smtp_obj.login(EMAIL_USERNAME, EMAIL_PASSWORD)
smtp_obj.sendmail(EMAIL_USERNAME, [RECIPIENT_EMAIL], msg.as_string())
smtp_obj.quit()
print("Email sent successfully.")
except Exception as e:
print(f"Failed to send email: {e}")
def execute_command_on_server(command):
"""Execute a command on the remote server via SSH."""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(SSH_HOST, port=SSH_PORT, username=SSH_USERNAME, password=SSH_PASSWORD)
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode('utf-8').strip()
client.close()
return output
def check_certificate_expiration():
"""Check if the certificate is about to expire and send an email alert."""
expiration_date = get_certificate_expiration(SERVER_URL)
days_until_expiration = (expiration_date - datetime.now()).days
if days_until_expiration <= WARNING_THRESHOLD_DAYS:
subject = f"Certificate Expiration Warning for {SERVER_URL}"
body = f"The SSL/TLS certificate for {SERVER_URL} will expire in {days_until_expiration} days."
send_email(subject, body)
if __name__ == "__main__":
# Run the certificate check script on the remote server via SSH
command = "python3 /path/to/your/check_certificate_script.py"
output = execute_command_on_server(command)
print(output)

Detailed Explanation

Configuration Parameters

SERVER_URL : The URL of the server whose certificate you want to check.

WARNING_THRESHOLD_DAYS : Number of days before expiration to trigger a warning (default 30).

EMAIL_HOST , EMAIL_PORT , EMAIL_USERNAME , EMAIL_PASSWORD , RECIPIENT_EMAIL : SMTP settings for sending alert emails.

SSH_HOST , SSH_PORT , SSH_USERNAME , SSH_PASSWORD : SSH connection details for the remote server.

SSH Login

The script uses the paramiko library to establish an SSH connection to the remote server and execute commands, returning the command output.

Certificate Checking

It uses the requests library to send an HTTPS request to the target URL, extracts the certificate via the underlying socket, and parses the notAfter field to determine the expiration date.

Email Alert

If the certificate is within the warning threshold, the script builds an email with smtplib and email modules and sends it to the configured recipient.

Conclusion

By following these steps, you can automatically log into a cloud server via SSH, run a certificate expiration check, and receive email notifications, helping you detect certificate issues early and avoid service interruptions.

operationsSSLSSHCertificate Monitoring
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.