贴一贴自己写的文件监控代码python

  1 '''

  2 Created on 2013-1-29

  3 

  4 @author: zsy

  5 '''

  6 import os.path

  7 import time

  8 import smtplib

  9 from email.mime.text import MIMEText

 10 from email.mime.multipart import MIMEMultipart

 11 from email.mime.audio import MIMEAudio

 12 

 13 class Scanner():  

 14     def isExists(self,saveFile):

 15         return os.path.isfile(saveFile)

 16     

 17     def getFileName(self,targetDir,whiteDir):

 18         export = []

 19         export_notime=[]

 20         for root, dirs, fileNames in os.walk(targetDir):

 21             for i,dirname in enumerate(dirs):

 22                 if dirname in whiteDir:del dirs[i]

 23             if fileNames:

 24                 for filename in fileNames:

 25                     filepath=os.path.join(root,filename)

 26                     if os.path.islink(filepath):

 27                         continue    

 28                     try:

 29                         filetime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.stat(filepath).st_mtime))

 30                         export.append(filepath+"------"+filetime+"\n")

 31                         export_notime.append(filepath)

 32                     except:

 33                         export.append(filepath+"\n")

 34                         export_notime.append(filepath)

 35         return export,export_notime

 36     

 37     def scan(self,targetDir,whiteDir, saveFile):

 38         file = open(saveFile, 'w')

 39         scanlist,scanlist_notime=self.getFileName(targetDir,whiteDir)

 40         for ifile in scanlist:

 41             try:

 42                 file.write(ifile)

 43             except:

 44                 file.write(ifile.encode('utf-8').decode('gbk'))

 45         file.close()

 46         return scanlist,scanlist_notime

 47     

 48     def rescan(self,targetDir,whiteDir,saveFile,changFile):

 49         #get filelist,filelist_notime from savefile

 50         filelist = []#filelist scanned before

 51         filelist_notime=[]

 52         read = open(saveFile, 'r')

 53         line = read.readline()

 54         while line:

 55             linenotime=line.split("------")[0]

 56             filelist.append(line)

 57             filelist_notime.append(linenotime)

 58             line = read.readline()

 59         read.close()

 60         #get scanlist,scanlist_notime from scan method

 61         scanlist,scanlist_notime = self.scan(targetDir,whiteDir,saveFile)#filelist scanned current

 62         

 63         #get deletelist,addlist,modifylist

 64         fileset = set(filelist)

 65         fileset_notime=set(filelist_notime)

 66         scanset = set(scanlist)

 67         scanset_notime=set(scanlist_notime)

 68     

 69         deletelist=[i for i in fileset_notime-scanset_notime]

 70             

 71         addlist_notime=[i for i in scanset_notime-fileset_notime]

 72         addlist=[]

 73         for item in addlist_notime:

 74             mtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.stat(item).st_mtime)) 

 75             addlist.append(item+"------"+mtime+"\n")

 76         

 77         modifylist=[i for i in scanset-fileset]   

 78         modifylist=[i for i in set(modifylist)-set(addlist)]  

 79           

 80         sendstr=""

 81         

 82         #write deletelist,addlist,modifylist to changefile and mail to manager

 83         if deletelist.__len__() > 0:

 84             fchange=open(changeFile,'a')

 85             title="\n"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" deleted files \n"

 86             fchange.write(title)

 87             sendstr+=title

 88             i=0

 89             for deletefile in deletelist:

 90                 

 91                 if ".js" in deletefile:

 92                     try:         

 93                         fchange.write(str(i)+" "+"js:************ "+deletefile.encode('utf-8').decode('gbk')+"\n")#update change_file

 94                     except:        

 95                         fchange.write(str(i)+" "+"js:************ "+deletefile+"\n")#update change_file    

 96                     sendstr+=str(i)+" "+"js:************* "+deletefile+"\n"

 97                     

 98                 elif "index." in deletefile:

 99                     try:         

100                         fchange.write(str(i)+" "+"index:********** "+deletefile.encode('utf-8').decode('gbk')+"\n")#update change_file

101                     except:         

102                         fchange.write(str(i)+" "+"index:********** "+deletefile+"\n")#update change_file    

103                     sendstr+=str(i)+" "+"index:********** "+deletefile+"\n"

104                     

105                 else:   

106                     try:         

107                         fchange.write(str(i)+" "+deletefile.encode('utf-8').decode('gbk')+"\n")#update change_file

108                     except:  

109                         fchange.write(str(i)+" "+deletefile+"\n")#update change_file    

110                     sendstr+=str(i)+" "+deletefile+"\n"

111                     

112                 i+=1

113             fchange.close()

114             

115         if addlist.__len__() > 0:

116             fchange=open(changeFile,'a')

117             title="\n"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" added files \n"

118             fchange.write(title)

119             sendstr+=title

120             i=0

121             for addfile in addlist:

122                 

123                 if ".js" in addfile:

124                     try:     

125                         fchange.write(str(i)+" "+"js:**************** "+addfile.encode('utf-8').decode('gbk'))#update change_file

126                     except:        

127                         fchange.write(str(i)+" "+"js:**************** "+addfile)#update change_file    

128                     sendstr+=str(i)+" "+"js:**************** "+addfile

129                     

130                 elif "index." in addfile:

131                     try:         

132                         fchange.write(str(i)+" "+"index:********** "+addfile.encode('utf-8').decode('gbk'))#update change_file

133                     except:        

134                         fchange.write(str(i)+" "+"index:********** "+addfile)#update change_file    

135                     sendstr+=str(i)+" "+"index:********** "+addfile

136                     

137                 else:

138                     try:          

139                         fchange.write(str(i)+" "+addfile.encode('utf-8').decode('gbk'))#update change_file

140                     except:      

141                         fchange.write(str(i)+" "+addfile)#update change_file    

142                     sendstr+=str(i)+" "+addfile

143                     

144                 i+=1

145             fchange.close()

146                     

147         if modifylist.__len__()>0:

148             fchange=open(changeFile,'a')

149             title="\n"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" modified files \n"

150             fchange.write(title)

151             sendstr+=title

152             i=0

153             for modifyfile in modifylist:

154                 

155                 if ".js" in modifyfile:

156                     try:       

157                         fchange.write(str(i)+" "+"js:************ "+modifyfile.encode('utf-8').decode('gbk'))#update change_file

158                     except:   

159                         fchange.write(str(i)+" "+"js:************ "+modifyfile)#update change_file   

160                     sendstr+=str(i)+" "+"js:************ "+modifyfile

161                     

162                 elif "index." in modifyfile:

163                     try:         

164                         fchange.write(str(i)+" "+"index:********** "+modifyfile.encode('utf-8').decode('gbk'))#update change_file

165                     except:       

166                         fchange.write(str(i)+" "+"index:********** "+modifyfile)#update change_file   

167                     sendstr+=str(i)+" "+"index:********** "+modifyfile

168                     

169                 else:

170                     try:      

171                         fchange.write(str(i)+" "+modifyfile.encode('utf-8').decode('gbk'))#update change_file

172                     except:       

173                         fchange.write(str(i)+" "+modifyfile)#update change_file   

174                     sendstr+=str(i)+" "+modifyfile

175                     

176                 i+=1

177             fchange.close()

178             

179         if sendstr.__len__()>0:

180             self.sendMail(sendstr)#send changefile to mail

181     

182     

183     def sendMail(self,body):

184         m=MIMEMultipart()

185         m['from']="TiaoZhanServer"

186         m['subject']="file_record_from_botwarden210"

187         m.attach(MIMEText(body,'plain','utf-8'))#charset

188         

189         smtpserver=smtplib.SMTP("smtp.163.com")

190         smtpserver.login('tiaozhan[email protected]', 'tiaozhan')

191         fromadd='[email protected]'

192         toadds=['[email protected]']

193         for toadd in toadds:

194             m['to']=toadd

195             smtpserver.sendmail(fromadd, toadd, m.as_string())   

196         smtpserver.close()

197 

198 if __name__ == '__main__':

199     Dir = '/home/www' 

200     whiteDir=["cache","data"]

201     myFile = '/home/zsy/FileRecord_py/file_record.txt'

202     changeFile="/home/zsy/FileRecord_py/file_change_record.txt"

203 

204 #    Dir = 'e:\\'

205 #    whiteDir=['myeclipseworkspace']

206 #    myFile = 'e:\\file_record.txt'

207 #    changeFile="e:\\file_change_record.txt" 

208 

209     scanner=Scanner()

210     if scanner.isExists(myFile):

211         scanner.rescan(Dir,whiteDir,myFile,changeFile)

212     else:

213         scanner.scan(Dir,whiteDir,myFile)        

主要用于监控web服务器上的web目录,防止被黑客修改文件或上传小马用。

file_record.txt用于记录当前目录下的所有文件。

file_change_record.txt用于记录本次扫描相对于上次扫描发生的改变。

其中特别对index和js文件做了明显的标记。index主要防止主页被篡改,js防止有恶意脚本。

完了会发邮件给指定的管理员邮箱。

后来知道linux下有自己的监控工具可以用,安装一下很方便。
http://www.cnblogs.com/peterpanzsy/archive/2013/05/18/3084961.html

 

你可能感兴趣的:(python)