SSL Expiration Checker
This utility checks the SSL certificate expiration dates for a list of domains. It helps system administrators monitor their websites and renew certificates before they expire.
Modules Used:
ssl: To wrap sockets and retrieve certificate information.- socket: To establish connections to the servers.
datetime: To parse dates and calculate the remaining time.- argparse: To handle command-line arguments.
The Code
Save this as ssl_check.py.
import ssl
import socket
import datetime
import argparse
import sys
def get_ssl_expiry_date(hostname, port=443):
context = ssl.create_default_context()
try:
# Create a connection to the host
with socket.create_connection((hostname, port), timeout=5) as sock:
# Wrap the socket with SSL
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
# Retrieve the certificate
cert = ssock.getpeercert()
# Extract the 'notAfter' date
# Format is usually: 'May 25 12:00:00 2024 GMT'
not_after = cert['notAfter']
# Parse the date string into a datetime object
expiry_date = datetime.datetime.strptime(not_after, r'%b %d %H:%M:%S %Y %Z')
return expiry_date
except Exception as e:
# Return None if connection fails or cert is invalid
return None
def check_domains(domains):
print(f"{'Domain':<30} {'Expiry Date':<25} {'Days Left':<10} {'Status'}")
print("-" * 80)
# Use UTC now because cert dates are in GMT/UTC
now = datetime.datetime.utcnow()
for domain in domains:
expiry = get_ssl_expiry_date(domain)
if expiry:
days_left = (expiry - now).days
expiry_str = expiry.strftime("%Y-%m-%d")
status = "OK"
if days_left < 0:
status = "EXPIRED"
elif days_left < 30:
status = "WARNING"
print(f"{domain:<30} {expiry_str:<25} {days_left:<10} {status}")
else:
print(f"{domain:<30} {'ERROR':<25} {'-':<10} {'Connection Failed'}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="SSL Expiration Checker")
parser.add_argument("domains", nargs='+', help="List of domains to check (e.g., google.com github.com)")
args = parser.parse_args()
check_domains(args.domains)
Usage
python ssl_check.py google.com github.com expired.badssl.com