用python监控日志,日志报错发送邮件给指定的邮箱,这个没法指定帐号密码,不知道为什么

# -*- coding: utf-8 -*-
# @Time    : 2023/8/4 10:15
# @Author  : hjcui
# @Site    : 
# @File    : Mail_Monitor.py
# @Software: PyCharm

import smtplib,time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

moni_file = r'./adapter_vid.log'
def Get_Msg():
    msg_list = []
    with open(moni_file,'rb') as fR:
        offset = -100
        while True:
            fR.seek(offset,2)
            lines = fR.readlines()
            if len(lines) >=2 :
                last_line = lines[-1]
                break
            offset *= 2
        if str(last_line).find('connection refused') != -1:
            msg = 'log error {}'.format(str(last_line))
        else:
            msg = 'process normal'

    return msg

def sendmail(host,mail_from,mail_to,msg):
        host_server = '172.17.0.145'
        sender = '[email protected]'
        receiver = ['[email protected]']
        mail_title = '{} 自动发送的邮件'.format(host_server)
        mail_content = msg
        msg = MIMEMultipart()
        msg['Subject'] = Header(mail_title,'utf-8')
        msg['From'] = sender
        msg['To'] = ";".join(receiver)
        msg.attach(MIMEText(mail_content,'plain','utf-8'))
        smtp = smtplib.SMTP(host_server,25,300)
        smtp.sendmail(sender,receiver,msg.as_string())
        smtp.quit()

if __name__ == '__main__':
        host_server = '172.17.0.145'
        sender = '[email protected]'
        receiver = '[email protected]'
        while True:
                msg = Get_Msg()
                if msg:
                    sendmail(host_server,sender,receiver,msg)
                time.sleep(86400)

你可能感兴趣的:(python,开发语言)