Practical Example: SSL Certificate Expiry Alerts
๐ท๏ธ Working with Dates and Time / Date Arithmetic with Timedelta
๐ Context Introduction
SSL certificates are the backbone of secure web communication. Every certificate has an expiration date, and letting one expire can cause service outages, security warnings, or complete loss of HTTPS functionality. As engineers, we need automated ways to check certificate expiry dates and receive alerts before they expire. This practical example combines Python's date and time capabilities with SSL certificate inspection to build a simple monitoring tool.
โ๏ธ How SSL Certificate Dates Work
When you connect to a secure website, the server presents its SSL certificate. This certificate contains two critical date fields:
- Not Before - The date when the certificate becomes valid
- Not After - The date when the certificate expires
Python's ssl and socket modules allow us to fetch this certificate information programmatically. We then use datetime and timedelta to calculate how many days remain until expiration.
๐ ๏ธ Building the SSL Expiry Checker
The script follows these steps:
- Connect to the target server using a secure socket connection
- Retrieve the SSL certificate and extract the expiry date
- Calculate days remaining by subtracting today's date from the expiry date
- Compare against a threshold (e.g., 30 days) to determine if an alert is needed
- Print the result with appropriate formatting
๐ Key Components Explained
| Component | Purpose |
|---|---|
| ssl.get_server_certificate() | Fetches the raw certificate from a server |
| datetime.strptime() | Converts the certificate date string into a datetime object |
| datetime.now() | Gets the current date and time |
| timedelta | Calculates the difference between two dates |
| .days attribute | Extracts the number of days from a timedelta object |
๐ต๏ธ Understanding the Date Calculation
The certificate expiry date comes in a specific format like "Dec 15 12:00:00 2025 GMT". To work with this date in Python, we must:
- Parse the string using strptime() with the format code "%b %d %H:%M:%S %Y %Z"
- Compare it to datetime.now() using subtraction
- The result is a timedelta object containing the difference in days
๐ง Practical Script Example
Here is the complete SSL expiry checker script. The script defines a function that takes a hostname and port, then returns the days until certificate expiration:
Step 1 - Import required modules: Import ssl, socket, and datetime at the top of your script.
Step 2 - Define the check function: Create a function called check_ssl_expiry that accepts hostname and port (default port 443) as parameters.
Step 3 - Establish connection: Use ssl.wrap_socket() with a socket connection to the target server. Set a timeout to avoid hanging on unresponsive servers.
Step 4 - Extract certificate: Call getpeercert() on the socket object to retrieve the certificate dictionary.
Step 5 - Parse expiry date: Access the "notAfter" key from the certificate dictionary. Convert this string to a datetime object using strptime() with the format "%b %d %H:%M:%S %Y %Z".
Step 6 - Calculate days remaining: Subtract datetime.now() from the parsed expiry date. Access the .days attribute of the resulting timedelta.
Step 7 - Return the result: Return the number of days as an integer. Close the socket connection.
Step 8 - Add alert logic: In the main part of the script, call the function for each server you want to monitor. Compare the returned days against a threshold (e.g., 30 days). Print a warning if the certificate expires within the threshold, or print a success message if it's still valid.
๐ Sample Output Structure
When you run the script, the output should look like this:
For a valid certificate: The output shows the hostname, the expiry date, and the number of days remaining. A green or neutral message indicates everything is fine.
For an expiring certificate: The output shows the same information but with a warning message indicating the certificate will expire soon. The number of days remaining is highlighted.
For an expired certificate: The output shows a critical alert with the number of days since expiration (negative value).
๐งช Testing with Real Servers
You can test the script with any HTTPS website. Common examples include:
- google.com - Usually has a long validity period
- github.com - Another reliable test target
- expired.badssl.com - A test site with an intentionally expired certificate
Each test will demonstrate different outputs based on the certificate's remaining validity.
๐ Extending the Script
Once the basic script works, you can extend it in several ways:
- Multiple servers: Store a list of hostnames in a configuration file and loop through them
- Email alerts: Integrate with smtplib to send email notifications when certificates are expiring
- Slack notifications: Use webhooks to post alerts to a Slack channel
- Logging: Write results to a log file with timestamps for historical tracking
- Scheduling: Use cron jobs or task schedulers to run the script daily
โ ๏ธ Important Considerations
- Network connectivity: The script requires outbound access to the target servers on port 443
- Firewall rules: Ensure your environment allows SSL connections to external hosts
- Rate limiting: Avoid checking the same server too frequently to prevent being blocked
- Certificate chains: This example checks only the leaf certificate, not the full chain
- Time zones: The certificate date is in GMT, so ensure your system time is accurate
๐ฏ Summary
This practical example demonstrates how Python's date and time capabilities solve a real-world infrastructure problem. By combining datetime, timedelta, and ssl modules, you can build a simple but effective SSL certificate monitoring tool. The same principles apply to any scenario where you need to calculate time differences, set reminders, or trigger actions based on dates. Start with this basic script, then customize it to fit your specific monitoring needs.
This example shows how to calculate days until an SSL certificate expires and trigger alerts using Python's datetime and timedelta.
๐ง Example 1: Calculate days until a certificate expires
This example demonstrates the basic calculation of remaining days from today to an expiry date.
from datetime import datetime, date
expiry_date = date(2025, 12, 31)
today = date.today()
days_remaining = (expiry_date - today).days
print(days_remaining)
๐ค Output: 365 (or the actual number of days from today)
๐ง Example 2: Check if a certificate is expired
This example shows how to compare a certificate's expiry date against today's date to determine if it has expired.
from datetime import date
expiry_date = date(2024, 1, 15)
today = date.today()
if expiry_date < today:
print("Certificate has expired")
else:
print("Certificate is still valid")
๐ค Output: Certificate has expired (if today is after Jan 15, 2024)
๐ง Example 3: Alert when certificate expires within 30 days
This example demonstrates how to trigger a warning when a certificate's expiry is approaching within a specific threshold.
from datetime import date, timedelta
expiry_date = date(2025, 6, 1)
today = date.today()
days_remaining = (expiry_date - today).days
alert_threshold = 30
if days_remaining <= alert_threshold:
print(f"ALERT: Certificate expires in {days_remaining} days")
else:
print(f"Certificate expires in {days_remaining} days โ no alert needed")
๐ค Output: ALERT: Certificate expires in 30 days (if today is May 2, 2025)
๐ง Example 4: Check multiple certificates and list those expiring soon
This example shows how to loop through a list of certificates and flag any that expire within a 60-day window.
from datetime import date
certificates = [
{"name": "example.com", "expiry": date(2025, 3, 15)},
{"name": "api.example.com", "expiry": date(2025, 8, 1)},
{"name": "mail.example.com", "expiry": date(2025, 2, 10)},
]
today = date.today()
alert_threshold = 60
for cert in certificates:
days_left = (cert["expiry"] - today).days
if days_left <= alert_threshold:
print(f"ALERT: {cert['name']} expires in {days_left} days")
else:
print(f"OK: {cert['name']} expires in {days_left} days")
๐ค Output: ALERT: example.com expires in 45 days (if today is Jan 29, 2025)
๐ง Example 5: Generate a daily report of certificate statuses
This example demonstrates how to create a summary report showing each certificate's status with days remaining and an alert level.
from datetime import date
certificates = [
{"name": "example.com", "expiry": date(2025, 4, 1)},
{"name": "api.example.com", "expiry": date(2025, 7, 15)},
{"name": "mail.example.com", "expiry": date(2025, 1, 20)},
]
today = date.today()
print("=== SSL Certificate Status Report ===")
print(f"Report Date: {today}")
print()
for cert in certificates:
days_left = (cert["expiry"] - today).days
if days_left < 0:
status = "EXPIRED"
elif days_left <= 30:
status = "CRITICAL"
elif days_left <= 60:
status = "WARNING"
else:
status = "OK"
print(f"{cert['name']:20s} | Days Left: {days_left:3d} | Status: {status}")
print()
print("=== End of Report ===")
๐ค Output: === SSL Certificate Status Report === (followed by a table of certificate statuses)
Comparison Table
| Feature | Basic Check | Alert Threshold | Multiple Certs | Daily Report |
|---|---|---|---|---|
| Days calculation | โ | โ | โ | โ |
| Expired detection | โ | โ | โ | โ |
| Custom threshold | โ | โ | โ | โ |
| Batch processing | โ | โ | โ | โ |
| Status levels | โ | โ | โ | โ |
๐ Context Introduction
SSL certificates are the backbone of secure web communication. Every certificate has an expiration date, and letting one expire can cause service outages, security warnings, or complete loss of HTTPS functionality. As engineers, we need automated ways to check certificate expiry dates and receive alerts before they expire. This practical example combines Python's date and time capabilities with SSL certificate inspection to build a simple monitoring tool.
โ๏ธ How SSL Certificate Dates Work
When you connect to a secure website, the server presents its SSL certificate. This certificate contains two critical date fields:
- Not Before - The date when the certificate becomes valid
- Not After - The date when the certificate expires
Python's ssl and socket modules allow us to fetch this certificate information programmatically. We then use datetime and timedelta to calculate how many days remain until expiration.
๐ ๏ธ Building the SSL Expiry Checker
The script follows these steps:
- Connect to the target server using a secure socket connection
- Retrieve the SSL certificate and extract the expiry date
- Calculate days remaining by subtracting today's date from the expiry date
- Compare against a threshold (e.g., 30 days) to determine if an alert is needed
- Print the result with appropriate formatting
๐ Key Components Explained
| Component | Purpose |
|---|---|
| ssl.get_server_certificate() | Fetches the raw certificate from a server |
| datetime.strptime() | Converts the certificate date string into a datetime object |
| datetime.now() | Gets the current date and time |
| timedelta | Calculates the difference between two dates |
| .days attribute | Extracts the number of days from a timedelta object |
๐ต๏ธ Understanding the Date Calculation
The certificate expiry date comes in a specific format like "Dec 15 12:00:00 2025 GMT". To work with this date in Python, we must:
- Parse the string using strptime() with the format code "%b %d %H:%M:%S %Y %Z"
- Compare it to datetime.now() using subtraction
- The result is a timedelta object containing the difference in days
๐ง Practical Script Example
Here is the complete SSL expiry checker script. The script defines a function that takes a hostname and port, then returns the days until certificate expiration:
Step 1 - Import required modules: Import ssl, socket, and datetime at the top of your script.
Step 2 - Define the check function: Create a function called check_ssl_expiry that accepts hostname and port (default port 443) as parameters.
Step 3 - Establish connection: Use ssl.wrap_socket() with a socket connection to the target server. Set a timeout to avoid hanging on unresponsive servers.
Step 4 - Extract certificate: Call getpeercert() on the socket object to retrieve the certificate dictionary.
Step 5 - Parse expiry date: Access the "notAfter" key from the certificate dictionary. Convert this string to a datetime object using strptime() with the format "%b %d %H:%M:%S %Y %Z".
Step 6 - Calculate days remaining: Subtract datetime.now() from the parsed expiry date. Access the .days attribute of the resulting timedelta.
Step 7 - Return the result: Return the number of days as an integer. Close the socket connection.
Step 8 - Add alert logic: In the main part of the script, call the function for each server you want to monitor. Compare the returned days against a threshold (e.g., 30 days). Print a warning if the certificate expires within the threshold, or print a success message if it's still valid.
๐ Sample Output Structure
When you run the script, the output should look like this:
For a valid certificate: The output shows the hostname, the expiry date, and the number of days remaining. A green or neutral message indicates everything is fine.
For an expiring certificate: The output shows the same information but with a warning message indicating the certificate will expire soon. The number of days remaining is highlighted.
For an expired certificate: The output shows a critical alert with the number of days since expiration (negative value).
๐งช Testing with Real Servers
You can test the script with any HTTPS website. Common examples include:
- google.com - Usually has a long validity period
- github.com - Another reliable test target
- expired.badssl.com - A test site with an intentionally expired certificate
Each test will demonstrate different outputs based on the certificate's remaining validity.
๐ Extending the Script
Once the basic script works, you can extend it in several ways:
- Multiple servers: Store a list of hostnames in a configuration file and loop through them
- Email alerts: Integrate with smtplib to send email notifications when certificates are expiring
- Slack notifications: Use webhooks to post alerts to a Slack channel
- Logging: Write results to a log file with timestamps for historical tracking
- Scheduling: Use cron jobs or task schedulers to run the script daily
โ ๏ธ Important Considerations
- Network connectivity: The script requires outbound access to the target servers on port 443
- Firewall rules: Ensure your environment allows SSL connections to external hosts
- Rate limiting: Avoid checking the same server too frequently to prevent being blocked
- Certificate chains: This example checks only the leaf certificate, not the full chain
- Time zones: The certificate date is in GMT, so ensure your system time is accurate
๐ฏ Summary
This practical example demonstrates how Python's date and time capabilities solve a real-world infrastructure problem. By combining datetime, timedelta, and ssl modules, you can build a simple but effective SSL certificate monitoring tool. The same principles apply to any scenario where you need to calculate time differences, set reminders, or trigger actions based on dates. Start with this basic script, then customize it to fit your specific monitoring needs.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
This example shows how to calculate days until an SSL certificate expires and trigger alerts using Python's datetime and timedelta.
๐ง Example 1: Calculate days until a certificate expires
This example demonstrates the basic calculation of remaining days from today to an expiry date.
from datetime import datetime, date
expiry_date = date(2025, 12, 31)
today = date.today()
days_remaining = (expiry_date - today).days
print(days_remaining)
๐ค Output: 365 (or the actual number of days from today)
๐ง Example 2: Check if a certificate is expired
This example shows how to compare a certificate's expiry date against today's date to determine if it has expired.
from datetime import date
expiry_date = date(2024, 1, 15)
today = date.today()
if expiry_date < today:
print("Certificate has expired")
else:
print("Certificate is still valid")
๐ค Output: Certificate has expired (if today is after Jan 15, 2024)
๐ง Example 3: Alert when certificate expires within 30 days
This example demonstrates how to trigger a warning when a certificate's expiry is approaching within a specific threshold.
from datetime import date, timedelta
expiry_date = date(2025, 6, 1)
today = date.today()
days_remaining = (expiry_date - today).days
alert_threshold = 30
if days_remaining <= alert_threshold:
print(f"ALERT: Certificate expires in {days_remaining} days")
else:
print(f"Certificate expires in {days_remaining} days โ no alert needed")
๐ค Output: ALERT: Certificate expires in 30 days (if today is May 2, 2025)
๐ง Example 4: Check multiple certificates and list those expiring soon
This example shows how to loop through a list of certificates and flag any that expire within a 60-day window.
from datetime import date
certificates = [
{"name": "example.com", "expiry": date(2025, 3, 15)},
{"name": "api.example.com", "expiry": date(2025, 8, 1)},
{"name": "mail.example.com", "expiry": date(2025, 2, 10)},
]
today = date.today()
alert_threshold = 60
for cert in certificates:
days_left = (cert["expiry"] - today).days
if days_left <= alert_threshold:
print(f"ALERT: {cert['name']} expires in {days_left} days")
else:
print(f"OK: {cert['name']} expires in {days_left} days")
๐ค Output: ALERT: example.com expires in 45 days (if today is Jan 29, 2025)
๐ง Example 5: Generate a daily report of certificate statuses
This example demonstrates how to create a summary report showing each certificate's status with days remaining and an alert level.
from datetime import date
certificates = [
{"name": "example.com", "expiry": date(2025, 4, 1)},
{"name": "api.example.com", "expiry": date(2025, 7, 15)},
{"name": "mail.example.com", "expiry": date(2025, 1, 20)},
]
today = date.today()
print("=== SSL Certificate Status Report ===")
print(f"Report Date: {today}")
print()
for cert in certificates:
days_left = (cert["expiry"] - today).days
if days_left < 0:
status = "EXPIRED"
elif days_left <= 30:
status = "CRITICAL"
elif days_left <= 60:
status = "WARNING"
else:
status = "OK"
print(f"{cert['name']:20s} | Days Left: {days_left:3d} | Status: {status}")
print()
print("=== End of Report ===")
๐ค Output: === SSL Certificate Status Report === (followed by a table of certificate statuses)
Comparison Table
| Feature | Basic Check | Alert Threshold | Multiple Certs | Daily Report |
|---|---|---|---|---|
| Days calculation | โ | โ | โ | โ |
| Expired detection | โ | โ | โ | โ |
| Custom threshold | โ | โ | โ | โ |
| Batch processing | โ | โ | โ | โ |
| Status levels | โ | โ | โ | โ |