python监控SSL证书到期时间

import ssl
import socket
import datetime
def getcertificateexpiry(domain):
try:
context = ssl.createdefaultcontext()
with socket.create_connection((domain, 443)) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssock:
cert = ssock.getpeercert()
expiry_date = datetime.datetime.strptime(cert[‘notAfter’], ‘%b %d %H:%M:%S %Y %Z’)
return expiry_date
except Exception as e:
print(f”Error fetching certificate for {domain}: {e}”)
return None
def main():
domain = “example.com” # Replace with your domain
expiry_date = get_certificate_expiry(domain)
if expiry_date:
remaining_days = (expiry_date - datetime.datetime.now()).days
threshold_days = 30 # Set your threshold here
if remaining_days <= threshold_days:
print(f”SSL certificate for {domain} will expire in {remaining_days} days. Please renew it!”)
if __name
== “__main
“:
main()