44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
import ssl
|
|
import socket
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
def check_certificate_expiry(hostname, port=443):
|
|
try:
|
|
# Crear un contexto SSL
|
|
context = ssl.create_default_context()
|
|
|
|
# Conectar al servidor y obtener el certificado
|
|
with socket.create_connection((hostname, port)) as sock:
|
|
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
|
|
cert = ssock.getpeercert()
|
|
|
|
# Obtener la fecha de expiración del certificado
|
|
expiry_date = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
|
|
|
|
# Obtener la fecha actual
|
|
current_date = datetime.utcnow()
|
|
|
|
# Calcular la diferencia en días
|
|
delta = expiry_date - current_date
|
|
days_until_expiry = delta.days
|
|
|
|
# Verificar si el certificado está a menos de 20 días de caducar
|
|
if days_until_expiry < 20:
|
|
print(f"CRITICAL: El certificado de {hostname} caduca en {days_until_expiry} días.")
|
|
sys.exit(2)
|
|
else:
|
|
print(f"OK: El certificado de {hostname} caduca en {days_until_expiry} días.")
|
|
sys.exit(0)
|
|
|
|
except Exception as e:
|
|
print(f"UNKNOWN: Error al verificar el certificado de {hostname}: {e}")
|
|
sys.exit(3)
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2:
|
|
print("Uso: python check_certificate.py <hostname>")
|
|
sys.exit(1)
|
|
|
|
hostname = sys.argv[1]
|
|
check_certificate_expiry(hostname) |