Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

Python Error handling in try block pass entry to array

I am ingesting a list of servers from a text file and using pyopenssl to resolve, connect,and retrieve the SSL Certificate information and passing my results to an array. It is working perfectly until one of my servers in the list does not resolve and I get a socket.gaierror error.

Although I can capture the error in the logs I am trying pass along something that will note the exception in my array results and that I will be able to pass to a table and send in an email. I want it to note in the host field "Unable to resolve" Can anyone point me towards a good way of accomplishing that? Thanks! Basic order of operations:

  1. Grab each host in the file

  2. Create an array to house the results

  3. Connect to server using SSL

  4. Get SSL info and close connection

  5. From SSL certificate get host name, expiration date, and decode

  6. Get date, format, and calculate number of days until SSL expires

  7. Record entry in the ssl_results array

     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:
        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()))
    
question from:https://stackoverflow.com/questions/66053019/python-error-handling-in-try-block-pass-entry-to-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...