简体   繁体   English

Python 尝试块传递条目到数组中的错误处理

[英]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.我正在从文本文件中提取服务器列表并使用 pyopenssl 来解析、连接和检索 SSL 证书信息并将我的结果传递给数组。 It is working perfectly until one of my servers in the list does not resolve and I get a socket.gaierror error.它运行良好,直到列表中的一台服务器无法解析并且我收到 socket.gaierror 错误。

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.虽然我可以在日志中捕获错误,但我正在尝试传递一些会在我的数组结果中记录异常的内容,并且我将能够传递给一个表并发送 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使用 SSL 连接到服务器

  4. Get SSL info and close connection获取 SSL 信息并关闭连接

  5. From SSL certificate get host name, expiration date, and decode从 SSL 证书获取主机名、到期日期和解码

  6. Get date, format, and calculate number of days until SSL expires获取日期、格式和计算 SSL 到期前的天数

  7. Record entry in the ssl_results array ssl_results 数组中的记录条目

     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. \n\n") 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('\nChecking 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. "\n\n") logger.warning(str(traceback.format_exc()))

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! \n\n")
    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('\nChecking 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, "\n\n")
    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?您还想要 email 客户端吗? Try this: https://realpython.com/python-send-email/试试这个: https://realpython.com/python-send-email/

I just need to add an exception for the socket.gaierror and update the array.我只需要为 socket.gaierror 添加一个异常并更新数组。

except socket.gaierror as e:
    ssl_results[str(ip)]['host'] = host
    ssl_results[str(ip)]['server_name'] = "Could not connect"
    ssl_results[str(ip)]['exp_date'] = 0
    ssl_results[str(ip)]['days_to_expire'] = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM