Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, February 20, 2025

Check certificate expiry using Python

 Following python script can use to check HTTPS certifcate expiry.

import ssl
import socket
import requests
from datetime import datetime

# Configuration
HOST = "mobitel.lk"  # Change to your domain
PORT = 443
THRESHOLD_DAYS = 30  # Alert before expiry (days)
API_URL = "https://your-api.com/alert"  # REST API to notify

def get_ssl_expiry(host, port):
    context = ssl.create_default_context()
    with socket.create_connection((host, port)) as sock:
        with context.wrap_socket(sock, server_hostname=host) as ssock:
            cert = ssock.getpeercert()
            expiry_date = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")
            return expiry_date

def send_alert():
    data = {"message": f"SSL certificate for {HOST} is expiring soon!"}
    response = requests.post(API_URL, json=data)
    print(f"Alert sent: {response.status_code}")
# Check expiry

expiry_date = get_ssl_expiry(HOST, PORT)
days_left = (expiry_date - datetime.now()).days
if days_left <= THRESHOLD_DAYS:
    send_alert()
    print(f"Certificate expiring in {days_left} days. Alert sent!")
else:
    print(f"Certificate is valid for {days_left} more days.")