Check for expiry SSL certificate with Python

๐Ÿ”’ How to Check SSL Certificate Expiry with Python

Ensuring your website’s SSL certificate is valid and up-to-date is crucial for maintaining security and user trust. An expired SSL certificate can cause browsers to flag your site as unsafe, which is not only bad for security but also terrible for business.

In this blog post, I'll show you how to use Python to check the expiry date of an SSL certificate — a useful tool for automating checks or adding to your DevOps monitoring.




๐Ÿงฐ What You’ll Need

  • Python 3 installed

  • ssl and socket (built-in Python modules)

๐Ÿงช Python Script to Check SSL Certificate Expiry

Here’s a simple script that checks the expiration date of a website's SSL certificate:

import ssl import socket from datetime import datetime def get_ssl_expiry(hostname, port=443): context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: cert = ssock.getpeercert() expiry_date_str = cert['notAfter'] expiry_date = datetime.strptime(expiry_date_str, '%b %d %H:%M:%S %Y %Z') return expiry_date def days_until_expiry(hostname): expiry_date = get_ssl_expiry(hostname) remaining = expiry_date - datetime.utcnow() return remaining.days # Example usage hostname = 'example.com' try: days_left = days_until_expiry(hostname) print(f"SSL certificate for {hostname} expires in {days_left} days.") except Exception as e: print(f"Error checking SSL certificate for {hostname}: {e}")

๐Ÿ“ Output

If the certificate is valid, you’ll see something like:

SSL certificate for example.com expires in 57 days.

If the certificate has already expired or is invalid, you’ll get an error message.


๐Ÿšจ Automate the Check

You can take this a step further by:

  • Scheduling the script to run daily with cron or Task Scheduler

  • Sending email alerts when expiry is near

  • Checking multiple domains from a list

Here's a simple extension that checks a list of domains:

domains = ['example.com', 'google.com', 'expired.badssl.com'] for domain in domains: try: days = days_until_expiry(domain) print(f"{domain}: {days} days remaining") except Exception as e: print(f"{domain}: ERROR - {e}")

Comments

Popular Posts