前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 监控文件变化

python 监控文件变化

作者头像
py3study
发布2020-01-07 14:55:19
1.5K0
发布2020-01-07 14:55:19
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
#!/usr/bin/env python
# encoding: utf-8
import time,os
import pyinotify
import smtplib
from email.mime.text import MIMEText
mailto_list=["695001606@qq.com"]
mail_host="smtp.163.com"
mail_user="cs@163.com"
mail_passwd="**********"
file = ['/usr/sbin/sshd','/var/log/syslog','/var/log/lastlog','/var/log/wtmp','/etc/passwd','/etc/shadow']
file1 = ['/usr/sbin/sshd','/etc/passwd','/etc/shadow']
def mail_send(to_list,sub,content):
    msg = MIMEText(content,_charset='utf-8')
    msg['Subject'] = sub
    msg['From'] = mail_user
    msg['To'] = ";".join(to_list)
    try:
        send_smtp = smtplib.SMTP()
        send_smtp.connect(mail_host)
        send_smtp.login(mail_user,mail_passwd)
        send_smtp.sendmail(mail_user,to_list,msg.as_string())
        send_smtp.close()
        return True
    except Exception,e:
        print str(e)
        return False


class handler(pyinotify.ProcessEvent):
    def process_IN_ATTRIB(self,event):
        if event.pathname in file:
            mail_send(mailto_list,'文件权限被修改',event.pathname)
    def process_IN_DELETE(self,event):
        if event.pathname in file:
            mail_send(mailto_list,"卧槽,文件被删除了",event.pathname)
        else:
            pass
    def process_IN_MODIFY(self,event):
        if event.pathname in file1:
            mail_send(mailto_list,"卧槽,文件被写东西了",event.pathname)
        else:
            pass
    def process_IN_MOVED_TO(self,event):
        if event.pathname in file:
            print(event.pathname)
            mail_send(mailto_list,"卧槽,文件被覆盖了",event.pathname)
        else:
            pass
    def process_IN_MOVED_FROM(self,event):
        if event.pathname in file:
            print(event.pathname)
            mail_send(mailto_list,"卧槽,文件被移走了",event.pathname)
        else:
            pass
def main():
    pathlist = ['/usr/sbin','/var/log','/etc']
    wm = pyinotify.WatchManager()
    wm.add_watch(pathlist,pyinotify.ALL_EVENTS,rec=True)
    en =handler()
    notifier= pyinotify.Notifier(wm,en)
    notifier.loop()
if __name__=='__main__':
    main()

要安装pyinotify模块

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档