first theres an Indent missing at the second try and except :-)
Isnt it just this simple:
import ssl
from datetime import datetime
import OpenSSL
import socket
from datetime import timedelta
import datetime
import traceback
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:% (message)s')
file_handler = logging.FileHandler('log/SSLNag.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
try:
ipfile = open('server_ip.txt')
cur_date = datetime.datetime.utcnow()
ssl_results = {}
except Exception as e:
logger.warning("ERROR ENCOUNTERED!
")
logger.warning(str(traceback.format_exc()))
for ip in ipfile:
global server_name, host, exp_date, days_to expire
ssl_results[str(ip)] = {'host': '', 'server_name': '',
'exp_date': '', 'days_to_expire': ''}
try:
host = ip.strip().split(':')[0]
port = ip.strip().split(':')[1]
print('
Checking certificate for server ', host)
ctx = OpenSSL.SSL.Context(ssl.PROTOCOL_TLSv1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
cnx = OpenSSL.SSL.Connection(ctx, s)
cnx.set_connect_state()
cnx.do_handshake()
cert = cnx.get_peer_certificate()
s.close()
server_name = cert.get_subject().commonName
print(server_name)
edate = cert.get_notAfter()
edate = edate.decode()
exp_date = datetime.datetime.strptime(edate, '%Y%m%d%H%M%SZ')
days_to_expire = int((exp_date - cur_date).days)
print(exp_date)
print('day to expire', days_to_expire)
ssl_results[str(ip)]['host'] = host
ssl_results[str(ip)]['server_name'] = server_name
ssl_results[str(ip)]['exp_date'] = exp_date
ssl_results[str(ip)]['days_to_expire'] = days_to_expire
except Exception as e:
logger.warning('Error on connection to Server,', str(ip))
logger.warning("ERROR ENCOUNTERED", host, "
")
logger.warning(str(traceback.format_exc()))
ssl_results[str(ip)]['host'] = "Unable to resolve"
ssl_results[str(ip)]['server_name'] = " "
ssl_results[str(ip)]['exp_date'] = " "
ssl_results[str(ip)]['days_to_expire'] = " "
Or what to you want to accomplish?
Do you also want the email client?
Try this:https://realpython.com/python-send-email/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…