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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonSSLSSHcertificate 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

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.