A simple file Integrity hash Verification script
#!/usr/bin/Env python#-*-coding:utf-8-*-Import osimport hashlibimport json# The list of all files in the site Directory path_list=[] #静态文件可以不做hash效验White_list=['. js','. jpg','. PNG','. html','. htm']def GetFile (path): forDirpath, Dirnames, filenamesinchOs.walk (path): forDirNameinchDirnames:dir=Os.path.join (Dirpath, dirname) #print dir path_list.append (dir) forFileNameinchFilenames:file=os.path.join (dirpath, filename)ifOs.path.splitext (file) [1] Notinchwhite_list: #print file path_list.append (file)returnpath_list# using a file iterator to loop through the data def md5sum (file): M=hashlib.md5 ()ifos.path.isfile (file): F=open (file,'RB') forLineinchf:m.update (line) F.closeElse: m.update (file)return(M.hexdigest ()) def get_md5result (Webpath): PathList=GetFile (webpath) md5_file={} forFileinchPathlist:md5_file[file]=md5sum (file) Json_data=json.dumps (md5_file) FileObject= Open ('Result.json','W') Fileobject.write (json_data) fileobject.close () def load_data (json_file): Model={} with open (Json_file,'R') asJson_file:model=json.load (json_file)returnmodeldef analysis_dicts (dict1,dict2): Keys1=Dict1.keys () keys2=Dict2.keys () Ret1= [I forIinchKeys1ifI notinchKeys2] Ret2= [I forIinchKeys2ifI notinchkeys1] Print u"files that may be deleted are:" forIinchret1:print i print u"The new files are:" forIinchret2:print i print u"files that may have been tampered with are:"Ret3=list ((Set(KEYS1). Union (Set(KEYS2))) ^(Set(keys1) ^Set(KEYS2))) forKeyinchRet3:ifKeyinchKeys1 and keyinchKeys2:ifDict1[key] = =Dict2[key]: PassElse: Print Keyif__name__ = ='__main__': Webpath= Raw_input ("Please enter your Web physical path, for example, C:\\wwww]. "). Lower () Get_md5result (webpath) Dict2=load_data ("Result.json") Methodselect= Raw_input ("[?] Check the integrity of the file: [Y]es or [N]o (y/n):"). Lower ()ifMethodselect = ='y': File=raw_input ("Please enter the hash of the file path to be compared:"). Lower () Dict1=load_data (file) analysis_dicts (dict1,dict2) elif Methodselect=='N': Exit ()
File Integrity Hash Verification Demo (Python script)