import ssl import socket import datetime import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def check_certificate_expiry(url, days_threshold=20): """Checks if a website's SSL certificate expires within the given threshold.""" try: hostname = url.split('//')[-1].split('/')[0] # Extract hostname port = 443 # Default HTTPS port 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.datetime.strptime(expiry_date_str, '%b %d %H:%M:%S %Y %Z') now = datetime.datetime.utcnow() time_remaining = expiry_date - now if time_remaining.days <= days_threshold: return url, expiry_date else: return None, None except (socket.gaierror, ConnectionRefusedError, ssl.SSLError, ValueError, IndexError) as e: # Handle potential errors print(f"Error checking {url}: {e}") return None, None def send_email(expired_certs, recipient_email="user@example.com", sender_email="your_email@example.com", sender_password="your_password"): """Sends an email with the list of expiring certificates.""" if not expired_certs: # Check if expired_certs is empty print("No certificates expiring soon.") return message = MIMEMultipart() message['From'] = sender_email message['To'] = recipient_email message['Subject'] = "Expiring SSL Certificates" email_body = "The following certificates are expiring soon:\n\n" for url, expiry_date in expired_certs: email_body += f"URL: {url}\nExpiry Date: {expiry_date}\n\n" message.attach(MIMEText(email_body, 'plain')) try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: # Example using Gmail, adjust as needed server.login(sender_email, sender_password) server.sendmail(sender_email, recipient_email, message.as_string()) print("Email sent successfully.") except Exception as e: print(f"Error sending email: {e}") def main(): """Reads URLs from a file, checks certificates, and sends an email.""" try: with open("urls.txt", "r") as f: # Replace "urls.txt" with your file name urls = [line.strip() for line in f] except FileNotFoundError: print("urls.txt file not found. Please create this file with your urls") return expiring_certificates = [] for url in urls: url_with_protocol = url if url.startswith("http://") or url.startswith("https://") else "https://" + url url_with_protocol = url_with_protocol.split("#")[0] #remove anchor links if present checked_url, expiry_date = check_certificate_expiry(url_with_protocol) if checked_url: expiring_certificates.append((checked_url, expiry_date)) send_email(expiring_certificates) if __name__ == "__main__": main()