Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ssl
- import socket
- import datetime
- import argparse
- import urllib.request
- import urllib.parse
- import pprint
- def get_ssl_expiry_date(hostname, port=443):
- """Gets the SSL certificate expiry date for a given hostname."""
- try:
- 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 = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
- return expiry_date, cert
- except Exception as e:
- print(f"Error: Could not retrieve SSL certificate for {hostname}: {e}")
- return None, None
- def check_expiry_and_notify(hostname, ntfy_topic, ntfy_server="https://ntfy.sh"):
- """Checks SSL expiry and sends a notification if it expires within a week."""
- expiry_date, cert = get_ssl_expiry_date(hostname)
- if expiry_date:
- print(f"Certificate details for {hostname}:")
- pprint.pprint(cert) #print the cert in a readable way.
- now = datetime.datetime.now()
- one_week_from_now = now + datetime.timedelta(weeks=1)
- if expiry_date < one_week_from_now:
- message = f"SSL certificate for {hostname} expires on {expiry_date.strftime('%Y-%m-%d %H:%M:%S')}"
- send_ntfy_notification(ntfy_server, ntfy_topic, message)
- print(f"Notification sent: {message}")
- else:
- print(f"SSL certificate for {hostname} expires after one week.")
- def send_ntfy_notification(server, topic, message):
- """Sends a notification to ntfy.sh using urllib."""
- url = f"{server}/{topic}"
- data = message.encode('utf-8')
- try:
- req = urllib.request.Request(url, data=data, method='POST')
- with urllib.request.urlopen(req) as response:
- if response.getcode() >= 400:
- print(f"ntfy request failed with status: {response.getcode()}")
- except urllib.error.URLError as e:
- print(f"Error sending ntfy notification: {e}")
- def main():
- parser = argparse.ArgumentParser(description="Check SSL certificate expiry and send ntfy notification.")
- parser.add_argument("hostname", help="The hostname to check.")
- parser.add_argument("ntfy_topic", help="The ntfy.sh topic to send notifications to.")
- parser.add_argument("--ntfy_server", default="https://ntfy.sh", help="The ntfy.sh server URL (default: https://ntfy.sh).")
- args = parser.parse_args()
- check_expiry_and_notify(args.hostname, args.ntfy_topic, args.ntfy_server)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement