So I wanted a quick way to create an MD5 sum of all the files recursively in a directory so i wrote a quick python script to do this.
Basically run the python file and provide the directory you want to check. This will create a new txt file named md5sYYYY-MM-DD-HHMM.txt containing a list of the files found along with their md5sums.
Then to check the the files run it again but provide the file instead of the directory.
It will also report if a file has been deleted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #!/usr/bin/env python # md5checker.py # version 1.0 # www.phillips321.co.uk import os,hashlib,time,sys def md5_file(file, block_size=2**20): try: f=open(file,'r') md5 = hashlib.md5() for chunk in iter(lambda: f.read(8192), b''): md5.update(chunk) f.close() return md5.hexdigest() except: return None def checkhashes(): allgood=0 print "[+]Scanning files from hashfile %s" % sys.argv[1] hashfile=open(sys.argv[1],'r') for line in hashfile.readlines(): oldhash,file=line.strip().split(',') if os.path.basename(file).startswith("md5s") == True : continue actualhash=md5_file(file) if actualhash==None: print "[!]File has been deleted: %s" % file elif oldhash != actualhash: print "[!]File has changed: %s" % file print " Old chesksum:" + oldhash print " New checksum:" + actualhash allgood+=1 hashfile.close() if allgood == 0: print "[+]No files changes" else: print "[!] %d file's has been changed!" % allgood def makehashes(): filename="md5s"+time.strftime("%Y-%m-%d-%H%M")+".txt" print "[+]No hashfile provided, creating new list\n-->" + filename hashfile=open(filename, "w+") for path, subFolders, files in os.walk(dir): for file in files: sys.stdout.write(" [-]"+os.path.join(path,file)) hash=md5_file(os.path.join(path,file)) print " - " + hash hashfile.write(hash+","+os.path.join(os.path.abspath(path),file+"\n")) hashfile.close() try: dir=os.path.join(sys.argv[1]) #directory provided except: dir=os.getcwd() #no directory provided (use current working dir) if os.path.isfile(os.path.join(dir)) == True: #file provided, run checkhashes os.path.isfile(os.path.join(dir)) checkhashes() else: #directory provided, run makehashes makehashes() |
Leave a Reply
You must be logged in to post a comment.