python监控文件与文件夹变化

发布时间:2019-08-02编辑:脚本学堂
python脚本监控文件变化,使用pyinotify模块监控文件与文件夹变化情况,二个实例代码。

1、python监控文件变化
 

复制代码 代码示例:
#!/usr/bin/env python
# encoding: utf-8

import time,os
import pyinotify
import smtplib
from email.mime.text import MIMEText

mailto_list=["12121212@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模块。

2、python监控文件夹变化

代码:
 

复制代码 代码示例:

#!/usr/bin/env python
# encoding:utf-8
 
import os
from  pyinotify import  WatchManager, Notifier, ProcessEvent,IN_DELETE, IN_CREATE,IN_MODIFY
 
class EventHandler(ProcessEvent):
"""事件处理"""
def process_IN_CREATE(self, event):
print   "Create file: %s "  %   os.path.join(event.path,event.name)

def process_IN_DELETE(self, event):
print   "Delete file: %s "  %   os.path.join(event.path,event.name)

def process_IN_MODIFY(self, event):
print   "Modify file: %s "  %   os.path.join(event.path,event.name)

def FSMonitor(path='/var/log'):# path:要监控的目录
wm = WatchManager()
mask = IN_DELETE | IN_CREATE |IN_MODIFY
notifier = Notifier(wm, EventHandler())
wm.add_watch(path, mask,rec=True)
print 'now starting monitor %s'%(path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break

if __name__ == "__main__":
FSMonitor()