Advertisement
Guest User

Untitled

a guest
May 18th, 2025
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.64 KB | None | 0 0
  1. import ssl
  2. import socket
  3. import datetime
  4. import argparse
  5. import urllib.request
  6. import urllib.parse
  7. import pprint
  8.  
  9. def get_ssl_expiry_date(hostname, port=443):
  10.     """Gets the SSL certificate expiry date for a given hostname."""
  11.     try:
  12.         context = ssl.create_default_context()
  13.         with socket.create_connection((hostname, port)) as sock:
  14.             with context.wrap_socket(sock, server_hostname=hostname) as ssock:
  15.                 cert = ssock.getpeercert()
  16.                 expiry_date = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
  17.                 return expiry_date, cert
  18.     except Exception as e:
  19.         print(f"Error: Could not retrieve SSL certificate for {hostname}: {e}")
  20.         return None, None
  21.  
  22. def check_expiry_and_notify(hostname, ntfy_topic, ntfy_server="https://ntfy.sh"):
  23.     """Checks SSL expiry and sends a notification if it expires within a week."""
  24.     expiry_date, cert = get_ssl_expiry_date(hostname)
  25.     if expiry_date:
  26.         print(f"Certificate details for {hostname}:")
  27.         pprint.pprint(cert) #print the cert in a readable way.
  28.         now = datetime.datetime.now()
  29.         one_week_from_now = now + datetime.timedelta(weeks=1)
  30.  
  31.         if expiry_date < one_week_from_now:
  32.             message = f"SSL certificate for {hostname} expires on {expiry_date.strftime('%Y-%m-%d %H:%M:%S')}"
  33.             send_ntfy_notification(ntfy_server, ntfy_topic, message)
  34.             print(f"Notification sent: {message}")
  35.         else:
  36.             print(f"SSL certificate for {hostname} expires after one week.")
  37.  
  38. def send_ntfy_notification(server, topic, message):
  39.     """Sends a notification to ntfy.sh using urllib."""
  40.     url = f"{server}/{topic}"
  41.     data = message.encode('utf-8')
  42.     try:
  43.         req = urllib.request.Request(url, data=data, method='POST')
  44.         with urllib.request.urlopen(req) as response:
  45.             if response.getcode() >= 400:
  46.                 print(f"ntfy request failed with status: {response.getcode()}")
  47.     except urllib.error.URLError as e:
  48.         print(f"Error sending ntfy notification: {e}")
  49.  
  50. def main():
  51.     parser = argparse.ArgumentParser(description="Check SSL certificate expiry and send ntfy notification.")
  52.     parser.add_argument("hostname", help="The hostname to check.")
  53.     parser.add_argument("ntfy_topic", help="The ntfy.sh topic to send notifications to.")
  54.     parser.add_argument("--ntfy_server", default="https://ntfy.sh", help="The ntfy.sh server URL (default: https://ntfy.sh).")
  55.  
  56.     args = parser.parse_args()
  57.  
  58.     check_expiry_and_notify(args.hostname, args.ntfy_topic, args.ntfy_server)
  59.  
  60. if __name__ == "__main__":
  61.     main()
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement