Emiliano
Emiliano

Reputation: 357

Python Recursive Hashlib

I'm having a problem for computing all checksums of all the files under the /bin/* directory. I'm implementing a HIDS in Python, so i need to compute the checksums of each file and save it, say, in a list .... so my code here only returns the first checksum of the /bin/* directory.

import sys
import haslib
path = sys.argv[1] #PATH OF THE FILES, ex: /etc/shadow, /bin/*, etc.

with open(path,'rb') as fh:
   md5 = hashlib.md5()
   while True:
      data = fh.read(8192)
      if not data:
         break
      md5.update(data)
print md5.hexdigest()

Any suggestions ??

Upvotes: 0

Views: 665

Answers (1)

salparadise
salparadise

Reputation: 5805

import sys
from os import listdir
from os.path import isfile, join
import hashlib
path = sys.argv[1] #PATH OF THE FILES, ex: /etc/shadow, /bin/*, etc.
files = [ f for f in listdir(path) if isfile(join(path,f)) ]
my_files = {}
for fil in files:
    with open(fil,'rb') as fh:
       md5 = hashlib.md5()
       while True:
          data = fh.read(8192)
          if not data:
             break
          md5.update(data)
    my_files[fil] = md5.hexdigest()
for k,v in my_files.iteritems():
    print 'file_name is {} | hash is {}'.format(k,v)

Upvotes: 1

Related Questions