python遍历文件并且进行md5计算

import os
import sys

dirPath = sys.argv[1]

def usage():
    print "python" + sys.argv[0] + "dirname"

class Encrypt(object):
    def __init__(self,dirName):
        self.dirName = dirName

    def getFileFromDir(self):
        dirPath = self.dirName
        allFiles = os.walk(dirPath)
        fileHandler = open('tmp.txt','wb')

        for pathName, dirList, fileList in allFiles:
            for fileName in fileList:
                singleFileName = fileName
                absFilePath = pathName + os.sep + singleFileName
                fileHandler.write(absFilePath+'\n')

    def md5Encrypt(self):
        import hashlib

        for fileName in file('tmp.txt', 'r').readlines():
            fileName = fileName.strip()
            md5Object = hashlib.md5()
            with open(fileName, 'rb') as f:
                md5Object.update(f.read())
                md5Hash = md5Object.hexdigest()
                print fileName+','+md5Hash

if __name__ == '__main__':
    if len(sys.argv) != 1:
        usage()
        
    en = Encrypt(dirName=dirPath)
    en.getFileFromDir()
    en.md5Encrypt()

  又从slqmap源码里面看到一个实现,还挺有意思的:

def md5File(filename):
    """
    Calculates MD5 digest of a file
    Reference: http://stackoverflow.com/a/3431838
    """

    checkFile(filename)

    digest = hashlib.md5()
    with open(filename, "rb") as f:
        for chunk in iter(lambda: f.read(4096), ""):
            digest.update(chunk)

    return digest.hexdigest()

  

posted @ 2018-07-23 16:13 webappsec93 阅读(...) 评论(...) 编辑 收藏