cmd執(zhí)行命令:python jiankong.py -w /root/視頻???????? //運行腳本(jiankong.py)監(jiān)控并時實刪除(/roo/視頻)目錄下的文件
Python os.rmdir() 方法:os.rmdir() 方法用于刪除指定路徑的目錄春哨。僅當這文件夾是空的才可以, 否則, 拋出OSError昆码。(http://www.runoob.com/python/os-rmdir.html)
python中os.path.isdir()等函數(shù)的作用和用法 :
一 用法和概念:
Python中的os模塊用于和系統(tǒng)進行交互,其中:
∫从恪1 os.listdir()用于返回一個由文件名和目錄名組成的列表,需要注意的是它接收的參數(shù)需要是一個絕對的路徑盖腕。
∨膊洹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):
????????"""事件處理"""
????????#創(chuàng)建
????????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)