Python学习之pyinotify监控Linux下文件,并实现邮件报警

来源:互联网 发布:xp打开1433端口 编辑:程序博客网 时间:2024/05/07 20:44

        实现功能:使用pyinotify监控httpd.conf,如果有修改,则与原文件对比,通过邮件报警,邮件内容格式采用HTML


整个功能分三部分:

环境:centos7     python2.7

目录结构:

   

一、邮件部分:

mail_send.py

#!/usr/bin/python
#coding:utf-8import smtplibfrom diff_file import betweenDifffrom email.mime.text import MIMETextmail_user = 'xxxxxxxxx@qq.com'mail_pass = 'xxxxxxxxxxx'mail_server = 'smtp.qq.com'mail_port = 465to_user = 'xxxxxxx@rongchat.com'def send_mail(title,content):    #创建一个实例,这里设置为html格式邮件    msg = MIMEText(content,_subtype = 'html',_charset = 'utf-8')    msg['Subject'] = title    msg['From'] = mail_user    msg['To'] = to_user    try:        #登录smtp服务器        server = smtplib.SMTP_SSL(mail_server,mail_port)        server.login(mail_user,mail_pass)        #邮件发送        server.sendmail(mail_user,to_user,msg.as_string())        server.quit()        return True    except Exception as e:        print(str(e))        return Falseif __name__ == '__main__':    monitor_files = '../jiankong/test.txt'    old_file = '../jiankong/test1.txt'    content = betweenDiff(old_file,monitor_files)    title = 'This is html file'    send_mail(title,content)


二、文件对比部分:

diff_file.py

#!/usr/bin/python
#coding:utf-8import difflibdef betweenDiff(fileone,filetwo):    with open(fileone) as f:        lines = f.readlines()    with open(filetwo) as f:        new_lines = f.readlines()    d = difflib.HtmlDiff()    html = d.make_file(lines,new_lines)    return htmlif __name__ == '__main__':    fileone = '../jiankong/test1.txt'    filetwo = '../jiankong/test.txt'    html = betweenDiff(fileone,filetwo)    print(html)

三、监控部分:

pyinotify_file.py

#!/usr/bin/python#coding:utf-8from diff_file import betweenDifffrom mail_send import send_mailfrom pyinotify import ProcessEvent,WatchManager,Notifier,ALL_EVENTSmonitor_dirs = ['../jiankong']monitor_files = ['../jiankong/test.txt']old_file = '../jiankong/test1.txt'class MyEvent(ProcessEvent):    def process_IN_MODIFY(self,event):        print('%s is %s.' %(event.pathname,event.maskname))        if event.pathname in monitor_files:            html = betweenDiff(old_file,event.pathname)            send_mail('The file content have been modified.',html)    def process_IN_ACCESS(self, event):        print('%s is %s.' %(event.pathname,event.maskname))def main():    vm = WatchManager()    vm.add_watch(monitor_dirs,ALL_EVENTS,rec = True)    en = MyEvent()    notifier = Notifier(vm,en)    notifier.loop()if __name__ == '__main__':    main()


运行pyinotify_file.py即可

阅读全文
0 0
原创粉丝点击