直接上代码了:

#!/usr/bin/env python
# -*- coding=utf-8 -*-
import smtplib
from email.mime.text import MIMEText
import threading
import time, datetime
import pyinotify


mailto_list = [""]  # 里面是对方的邮箱
# -----------QQ邮箱发送设置----------------------
mail_server = "smtp.qq.com"  # 以qq邮箱为例子,里面是QQ邮箱的服务,换成其他邮箱需要更改服务
mail_user = ""  # 这是QQ邮箱的账号
mail_pass = ""  # 如果是其他的可以直接填上密码,如果用qq之类的,或者邮箱未开服务,会提醒你打开下面的链接


now = int(time.time())
timeStruct = time.localtime(now)
strTime = time.strftime("%Y-%m-%d", timeStruct)
log_name = '/var/log/%s.log'%strTime

# QQ邮箱需要去官方打开服务:http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
def send_mail(to_list, sub, content):
    msg = MIMEText(content, 'plain', 'utf-8')
    msg["Accept-Language"] = "zh-CN"
    msg["Accept-Charset"] = "ISO-8859-1,utf-8"
    msg['Subject'] = sub
    msg['From'] = mail_user
    msg['To'] = ";".join(to_list)
    try:
        #server = smtplib.SMTP()
        server = smtplib.SMTP_SSL(mail_server, 465)
        server.connect(mail_server)
        #server.starttls()
        server.login(mail_user, mail_pass)
        server.sendmail(mail_user, to_list, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False


def get_date():
    return str(datetime.datetime.utcfromtimestamp(time.time()) + datetime.timedelta(hours=8))


def send_warning_mail(title, info):
    now_time = get_date()
    try:
        t = threading.Thread(target=send_mail, args=(mailto_list, title, str(now_time) + "                   内容如下:             " + str(info)))
        t.start()
    except:
        pass


def read_log():
    with open(log_name,'r') as f:
        content = f.read()
        send_warning_mail('检测到log文件发生变化', "\n%s"%content)


class MyEventHandler(pyinotify.ProcessEvent):
     
    #当文件被修改时调用函数
    def process_IN_MODIFY(self, event):
        try:
            read_log()
        except Exception,e:
            print str(e)


def main_pro():
    read_log()
    wm = pyinotify.WatchManager()
    wm.add_watch(log_name, pyinotify.ALL_EVENTS, rec=True)
    eh = MyEventHandler()
 
    # notifier
    notifier = pyinotify.Notifier(wm, eh)
    notifier.loop()
    
if __name__ == '__main__':
    main_pro()

上面的代码优化空间非常大,有需要的可以自己优化下,比如文件增大如何处理,如何只读取文件新内容等等!
https://www.cnblogs.com/iamlehaha/articles/6790700.html

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐