cmd执行命令:python jiankong.py -w /root/视频 //运行脚本(jiankong.py)监控并时实删除(/roo/视频)目录下的文件
Python os.rmdir() 方法:os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。(http://www.runoob.com/python/os-rmdir.html)
python中os.path.isdir()等函数的作用和用法 :
一 用法和概念:
Python中的os模块用于和系统进行交互,其中:
1 os.listdir()用于返回一个由文件名和目录名组成的列表,需要注意的是它接收的参数需要是一个绝对的路径。
2 os.path.isdir()用于判断对象是否为一个目录。
3 os.path.isfile()用于判断对象是否为一个文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ** Author: ssooking
importos
importargparse
frompyinotify importWatchManager, Notifier,ProcessEvent
frompyinotify importIN_DELETE, IN_CREATE,IN_MOVED_TO,IN_ATTRIB
classEventHandler(ProcessEvent):
"""事件处理"""
#创建
defprocess_IN_CREATE(self, event):
print"[!] Create : "+event.pathname
DeleteFileOrDir(event.pathname)
#删除
defprocess_IN_DELETE(self, event):
print"[!] Delete : "+event.pathname
#文件属性被修改,如chmod、chown命令
defprocess_IN_ATTRIB(self, event):
print"[!] Attribute been modified:"+event.pathname
#文件被移来,如mv、cp命令
defprocess_IN_MOVED_TO(self, event):
print"[!] File or dir been moved to here: "+event.pathname
DeleteFileOrDir(event.pathname)
defDeleteFileOrDir(target):
ifos.path.isdir(target):
fileslist =os.listdir(target)
forfiles infileslist:
DeleteFileOrDir(target +"/"+files)
try:
os.rmdir(target)
print" >>> Delete directory successfully: "+target
except:
print" [-] Delete directory failed: "+target
ifos.path.isfile(target):
try:
os.remove(target)
print" >>> Delete file successfully"+target
except:
print" [-] Delete file filed: "+target
defMonitor(path):
wm =WatchManager()
mask =IN_DELETE | IN_CREATE | IN_MOVED_TO | IN_ATTRIB
notifier =Notifier(wm, EventHandler())
wm.add_watch(path, mask,rec=True)
print'[+] Now Starting Monitor: %s'%(path)
whileTrue:
try:
notifier.process_events()
ifnotifier.check_events():
notifier.read_events()
exceptKeyboardInterrupt:
notifier.stop()
break
if__name__ =="__main__":
parser =argparse.ArgumentParser(
usage="%(prog)s -w [path]",
description=('''
Introduce:Simple Directory Monitor! by ssooking''')
)
parser.add_argument('-w','--watch',action="store",dest="path",default="/var/www/html/",help="directory to watch,default is /var/www/html")
args=parser.parse_args()
Monitor(args.path)