fwarren

Send email of expiring letsencrypt certs

Feb 4th, 2025
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.14 KB | None | 0 0
  1. import ssl
  2. import socket
  3. import datetime
  4. import smtplib
  5. from email.mime.text import MIMEText
  6. from email.mime.multipart import MIMEMultipart
  7.  
  8. def check_certificate_expiry(url, days_threshold=20):
  9.     """Checks if a website's SSL certificate expires within the given threshold."""
  10.     try:
  11.         hostname = url.split('//')[-1].split('/')[0]  # Extract hostname
  12.         port = 443  # Default HTTPS port
  13.  
  14.         context = ssl.create_default_context()
  15.         with socket.create_connection((hostname, port)) as sock:
  16.             with context.wrap_socket(sock, server_hostname=hostname) as ssock:
  17.                 cert = ssock.getpeercert()
  18.  
  19.         expiry_date_str = cert['notAfter']
  20.         expiry_date = datetime.datetime.strptime(expiry_date_str, '%b %d %H:%M:%S %Y %Z')
  21.         now = datetime.datetime.utcnow()
  22.         time_remaining = expiry_date - now
  23.        
  24.         if time_remaining.days <= days_threshold:
  25.             return url, expiry_date
  26.         else:
  27.             return None, None
  28.     except (socket.gaierror, ConnectionRefusedError, ssl.SSLError, ValueError, IndexError) as e:  # Handle potential errors
  29.         print(f"Error checking {url}: {e}")
  30.         return None, None
  31.  
  32.  
  33. def send_email(expired_certs, recipient_email="[email protected]", sender_email="[email protected]", sender_password="your_password"):
  34.     """Sends an email with the list of expiring certificates."""
  35.  
  36.     if not expired_certs:  # Check if expired_certs is empty
  37.         print("No certificates expiring soon.")
  38.         return
  39.  
  40.     message = MIMEMultipart()
  41.     message['From'] = sender_email
  42.     message['To'] = recipient_email
  43.     message['Subject'] = "Expiring SSL Certificates"
  44.  
  45.     email_body = "The following certificates are expiring soon:\n\n"
  46.     for url, expiry_date in expired_certs:
  47.         email_body += f"URL: {url}\nExpiry Date: {expiry_date}\n\n"
  48.  
  49.     message.attach(MIMEText(email_body, 'plain'))
  50.  
  51.     try:
  52.         with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:  # Example using Gmail, adjust as needed
  53.             server.login(sender_email, sender_password)
  54.             server.sendmail(sender_email, recipient_email, message.as_string())
  55.         print("Email sent successfully.")
  56.     except Exception as e:
  57.         print(f"Error sending email: {e}")
  58.  
  59.  
  60.  
  61. def main():
  62.     """Reads URLs from a file, checks certificates, and sends an email."""
  63.  
  64.     try:
  65.         with open("urls.txt", "r") as f:  # Replace "urls.txt" with your file name
  66.             urls = [line.strip() for line in f]
  67.     except FileNotFoundError:
  68.         print("urls.txt file not found. Please create this file with your urls")
  69.         return
  70.  
  71.     expiring_certificates = []
  72.     for url in urls:
  73.         url_with_protocol = url if url.startswith("http://") or url.startswith("https://") else "https://" + url
  74.         url_with_protocol = url_with_protocol.split("#")[0] #remove anchor links if present
  75.  
  76.         checked_url, expiry_date = check_certificate_expiry(url_with_protocol)
  77.         if checked_url:
  78.             expiring_certificates.append((checked_url, expiry_date))
  79.  
  80.     send_email(expiring_certificates)
  81.  
  82.  
  83. if __name__ == "__main__":
  84.     main()
Advertisement
Add Comment
Please, Sign In to add comment