文件监控脚本源码

2017-01-11 12:25:35来源:作者:人点击

第七城市
#!/usr/bin/env python# coding:utf-8import sys, os, time, json, re, datetime, urllib, urllib2,MySQLdb,promonreload(sys)sys.setdefaultencoding('utf8')class main(object): def __init__(self, path, filename='', updatefile=1, delfile=1, modifyfile=1, size=1,time_interval="60",start_time="00:00", end_time='23:59',includeChild=1):self.path = path  # 路径,#print self.pathif notos.path.isdir(path):print "要监控的dir不存在"self.filename = filenameself.updatefile = updatefileself.delfile = delfileself.modifyfile=modifyfile  # 修改文件self.time_interval = time_interval  # 执行时间间隔self.start_time = start_time  # 开始执行时间段self.end_time=end_time #结束执行时间段self.size=sizeself.includeChild=includeChild#子目录print includeChild,"1监控子目录,0不监控" def get_all_file(self):alllist=[]all=os.walk(self.path)flag = Truefor i in all:#print iif self.includeChild == 0: flag =Falseif i[2]: for x in i[2]:alllist.append("%s/%s"%(i[0],x))if not flag: breakprint self.filenameif self.filename and type(self.filename)==list:alllist=self.filenameprint "只监控指定文件",alllistprint alllistif not os.path.isdir("db"):os.makedirs("db")else:with open("db/filenum","w") as f: dic={} #dic[alllist]=len(alllist) dic[len(alllist)]=alllist dic = json.dumps(dic) f.write(dic)return alllist def read_file_add_del(self):if not os.path.isdir("db"):os.makedirs("db")if os.path.isfile("db/filenum"):with open("db/filenum") as f: for i in f:if not  i.strip():continueread_info=json.loads(i)num=read_info.keys()if num:num=int(num[0])read_filelist=read_info[str(num)]return read_filelistreturn None def bijiao_file_add_del(self):sj_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")read_info=self.read_file_add_del()get_info=self.get_all_file()if read_info:for i in read_info: if i.strip() not in get_info:if self.includeChild==0:file_name=str(i).replace(self.path,'')file_name=file_name.replace(file_name[0],'')if '/' in file_name: passif self.delfile==1:print i,"这个文件被删除了,时间:%s"%(sj_time)# 调用发监控脚本的地方promon.main(i,"del %s"%sj_time)else:print "没有监控文件删除"#print get_infofor x in get_info: if self.includeChild==0:file_name = str(x).replace(self.path, '')file_name = file_name.replace(file_name[0], '')#print file_nameif '/' in file_name:print '不监控子目录', xcontinue if x not  in read_info:if self.updatefile==1:print x,"这个文件,是增加的,时间:%s"%(sj_time)#调用发监控脚本的地方promon.main(x, "add %s" % sj_time)else:print "没有监控文件增加" def get_file_info(self,filename):print filename,self.pathif "/" not in filename:filename="%s/%s"%(self.path,filename)try:fileStats = os.stat(filename)# 定义一个字典except Exception:print filename,"不存在"promon.main(filename,"del")return FalsefileInfo = {'filename': filename,'Size': fileStats.st_size,  # 获取文件大小'LastModified': fileStats.st_mtime,  # 获取文件最后修改时间'LastAccessed': fileStats.st_atime,  # 获取文件最后访问时间'CreationTime': fileStats.st_ctime,  # 获取文件创建时间'Mode': fileStats.st_mode  # 获取文件的模式}return fileInfo hostname = os.popen('hostname').read().strip() def insert_fileinfo(self):filelist=self.get_all_file()jiaoben_name=sys.argv[0 ]for filename in filelist:fileinfo=self.get_file_info(filename)if filename: filesize=fileinfo['Size'] LastModified=fileinfo['LastModified'] LastAccessed=fileinfo['LastAccessed'] CreationTime=fileinfo['CreationTime'] updatetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") sql='''insert into fileinfo (hostname,filename,filesize,LastModified,LastAccessed,CreationTime,updatetime,monit_name) values ('%s','%s','%s','%s','%s','%s','%s','%s')'''/%(self.hostname,filename,filesize,LastModified,LastAccessed,CreationTime,updatetime,jiaoben_name) #print sql self.select_sql(sql) def select_sql(self,sql):conn = MySQLdb.connect(host='192.168.1.203', port=3306, user='root', passwd='root',db='selfservice', charset='UTF8')cur = conn.cursor()#print sqlcur.execute(sql)conn.commit()cur.close()conn.close()for i in cur:data=iif data: return data def bijiao_fileinfo(self):filelist = self.get_all_file()for filename in filelist:file_name=filename.replace(self.path,'')file_name=file_name.replace(file_name[0],'')#print file_nameif '/' in file_name: print self.includeChild if self.includeChild==0:passif len(filename.strip())==0: continueupdatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")sql='''select * from fileinfo where filename='%s'/and updatetime<'%s' and hostname='%s' order by id desc limit 1'''%(filename,updatetime,self.hostname)newinfo=self.select_sql(sql)sjc=time.time()x = time.localtime(sjc - 60)#秒updatetime5=time.strftime('%Y-%m-%d %H:%M:%S',x)sql = '''select * from fileinfo where filename='%s'/ and updatetime<'%s' and hostname='%s' order by id desc limit 1''' % (filename, updatetime5, self.hostname)try: laoinfo = self.select_sql(sql)except Exception,e: print eelse: if not laoinfo:continue if laoinfo[3]!=newinfo[3]:if self.modifyfile==1:sj_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")print filename,"这个文件被修改了,时间:%s"%datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")# 调用发监控脚本的地方promon.main(filename, "modifyfile %s" % sj_time)else:print "虽然被修改了,但是没有监控" if laoinfo[2] != newinfo[2]:if self.size==1:sj_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")print filename, "这个文件大小变了,时间:%s" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")# 调用发监控脚本的地方promon.main(filename, "size %s" % sj_time)else:print "虽然大小变了,但是没有监控" def panduanjiankong(self):if self.filename:for i in self.filename: filepath="%s/%s"(self.path,i) sql='''delete from fileinfo where hostname='%s' and filename<>'%s' '''%(self.hostname,filepath) self.insert_mysql(sql)#if self.includeChild==0: #filelist=self.get_all_file()  #  for x in filelist:#  filename=str(x).replace(self.path,'')# if '/' in filename: # sql = '''delete from fileinfo where hostname='%s' and filename<>'%s' ''' % (self.hostname, x)  #self.insert_mysql(sql)def get_conf_info(): jiaoben_name=sys.argv[0] conf=jiaoben_name.replace(".py",".txt") if os.path.isfile(conf):with open(conf) as f:for i in f: if i.strip():conf_info = json.loads(i)#print conf_inforeturn conf_info else:print "配置文件不存在"if __name__=="__main__": while True:conf=get_conf_info()filePath=conf["filePath"]fileName=conf["fileName"]mcInterval=int(conf["mcInterval"])#时间间隔includeChild=int(conf["includeChild"])#子目录add=int(conf["add"])modify=int(conf["modify"])#修改remove=int(conf["remove"])size=int(conf["size"])alarmBTime=int(conf["alarmBTime"])alarmETime=int(conf["alarmETime"])dq_time=int(datetime.datetime.now().strftime("%H%M"))#print conftry:if dq_time>alarmBTime and dq_time<alarmETime: obj=main(filePath,filename=fileName,updatefile=add,delfile=remove,modifyfile=modify,size=size,start_time=alarmBTime,end_time=alarmETime,includeChild=includeChild) obj.bijiao_file_add_del() obj.insert_fileinfo() #obj.panduanjiankong() obj.bijiao_fileinfo()except Exception,e:print etime.sleep(mcInterval*30)
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台