Abajo les dejo un script realizado en Python3 que chequea fecha de vencimiento de certificados SSL (https) y realiza el envio de correos.
Importante:
Que corra en OS modernos (Ubuntu 16.04 o mayor por ejemplo).., la razón es el soporte de librerías actualizadas SSL
El Script:
$ more check_ssl_certificates.py
#!/usr/bin/python3
#El objetivo de este script es revisar los hostnames en la lista hostnames
#revisar cuantos dias faltan para que expire el certificado SSL
#y se expira pronto (definido por la variable umbral) enviar un correo
#con dicha notificacion
import OpenSSL
import ssl, socket
import argparse
from OpenSSL import SSL
from datetime import datetime
# Please add every FQDN you wish to be checked
hostnames = ["www.sitio1.com","www.sitio2.com","www.sitio3.com"]
umbral = 10 #threshold - number of days left in order to send the notification
notify_to= "you@yourserver.com, youyou@yourserver.com" #list of email addresses to send email separated by ,
def cert_expiration_date(hostname):
# get SSL Cert info
try:
cert = ssl.get_server_certificate((hostname, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
x509info = x509.get_notAfter()
exp_day = x509info[6:8].decode('utf-8')
exp_month = x509info[4:6].decode('utf-8')
exp_year = x509info[:4].decode('utf-8')
exp_date = str(exp_day) + ' ' + str(exp_month) + ' ' + str(exp_year)
expire_date = datetime.strptime(exp_date, "%d %m %Y")
except Exception:
MSG='el host ' + str(hostname) + ' no pudo ser chequeado '
sendnotification(hostname, 0, MSG)
return #will enter here if could not connect to the website port 443
#print('SSL Certificate for hostname', hostname, 'will be expired on (DD-MM-YYYY)', exp_date)
#print('SSL Certificate for hostname', hostname, 'will be expired on (DD-MM-YYYY)', expire_date)
expire_in = expire_date - datetime.now()
expire_in = str(expire_in).split(' ')[0]
if int(expire_in) < umbral :
MSG='el cert ssl de ' + str(hostname) + ' expira en ' + str(expire_in) + ' dias'
sendnotification(hostname, str(expire_in), MSG)
#print ('Expira en: ', expire_in)
def sendnotification(hostname, expire_in, MSG):
from smtplib import SMTP_SSL as SMTP
import logging
import logging.handlers
import sys
from email.mime.text import MIMEText
#MSG = 'el cert ssl de ' + str(hostname) + ' expira en ' + str(expire_in) + ' dias'
#text = MSG
msg = MIMEText(MSG, 'plain')
msg['Subject'] = MSG
me = 'your@email.com'
recipients = notify_to
msg['To'] = notify_to
try:
conn = SMTP('yourmailserver.com')
conn.set_debuglevel(True)
conn.login('authusr', 'yourpassword')
try:
conn.sendmail(me,recipients.split(',') , msg.as_string())
finally:
conn.close()
except Exception as exc:
logger.error("ERROR!!!")
logger.critical(exc)
sys.exit("Mail failed: {}".format(exc))
if __name__ == "__main__":
for hostname in hostnames:
cert_expiration_date(hostname)
No hay comentarios:
Publicar un comentario
¿Algo adicional que quieras mencionar? ¿Algun consejo?, ¿truco? Gracias!