How to send output from a python script to an email address

后端 未结 6 772
野性不改
野性不改 2021-02-05 22:38

I have a threaded python script that pings 20 nodes on a local area network, and prints out the status of each: Node is Alive, Node is Down, etc.. I would like to have this outp

6条回答
  •  一生所求
    2021-02-05 23:16

    Take a look at the logging and logging.config, I've used this before to receive error messages from a script running in the background

    http://docs.python.org/library/logging.html

    For example

    import logging
    import logging.config
    
    logDir = "./logs/"
    
    logging.config.fileConfig(logDir+'logging.conf')
    logger = logging.getLogger('email')
    
    logger.debug('THIS IS A DEBUG MESSAGE')
    logger.error('THIS IS AN ERROR')
    

    And then the logging.conf

    [loggers]
    keys=root,email
    
    [logger_root]
    level=DEBUG
    handlers=rotatingFileHandler
    
    [logger_email]
    level=ERROR
    handlers=email
    qualname=email
    
    [formatters]
    keys=emailFormatter,rotatingFormatter
    
    [formatter_emailFormatter]
    format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
    
    [formatter_rotatingFormatter]
    format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
    datefmt=%m-%d %H:%M
    
    [handlers]
    keys=email,rotatingFileHandler
    
    [handler_email]
    class=handlers.SMTPHandler
    level=ERROR
    formatter=emailFormatter
    args=('mail.xxx','x@x.com',['y@y.com',],'ERROR!',('x@x.com','xxx'))
    
    [handler_rotatingFileHandler]
    class=handlers.RotatingFileHandler
    level=DEBUG
    formatter=rotatingFormatter
    args=('./logs/log.out', 'maxBytes=1000000', 'backupCount=5')
    

    From the above I would receive "THIS IS AN ERROR" in my email.

提交回复
热议问题