Python Script to Retrieve Domain SSL Certificate Expiration Date and Remaining Days
This article presents a Python script that retrieves a domain's SSL certificate information, parses its start and expiration dates, converts them to datetime objects, and calculates the remaining days until the certificate expires, providing a simple command‑line tool for monitoring certificate validity.
This article provides a Python script that obtains a domain name, executes a curl command to fetch SSL certificate details, parses the start and expiration dates, converts them to datetime objects, and calculates the remaining days until expiration.
The script imports necessary modules, defines a main(domain) function, uses subprocess.getstatusoutput to run curl -Ivs https://{domain} --connect-timeout 10 , captures the output, and extracts fields with a regular expression.
It then converts the extracted date strings using time.strptime and datetime.strptime , formats them, computes the difference between the expiration date and the current time, and returns the number of days remaining.
When run as a script, it reads the domain from command‑line arguments, calls main , and prints the remaining days.
import re
import sys
import time
import subprocess
from datetime import datetime
from io import StringIO
def main(domain):
f = StringIO()
comm = f"curl -Ivs https://{domain} --connect-timeout 10"
result = subprocess.getstatusoutput(comm)
f.write(result[1])
try:
m = re.search('start date: (.*?)\n.*?expire date: (.*?)\n.*?common name:(.*?)\n.*?issuer: CN=(.*?)\n', f.getvalue(), re.S)
start_date = m.group(1)
expire_date = m.group(2)
common_name = m.group(3)
issuer = m.group(4)
except Exception as e:
return 999999999
start_date = time.strptime(start_date, "%b %d %H:%M:%S %Y GMT")
start_date_st = time.strftime("%Y-%m-%d %H:%M:%S", start_date)
expire_date = datetime.strptime(expire_date, "%b %d %H:%M:%S %Y GMT")
expire_date_st = datetime.strftime(expire_date, "%Y-%m-%d %H:%M:%S")
remaining = (expire_date - datetime.now()).days
return remaining
if __name__ == "__main__":
domain = sys.argv[1]
remaining_days = main(domain)
print(remaining_days)Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.