【问题标题】:Python Recursive HashlibPython 递归哈希库
【发布时间】:2014-06-06 05:33:03
【问题描述】:

我在计算 /bin/* 目录下所有文件的所有校验和时遇到问题。 我在 Python 中实现了一个 HIDS,所以我需要计算每个文件的校验和并将其保存在一个列表中……所以我的代码只返回 /bin/* 目录的第一个校验和。

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()

有什么建议吗??

【问题讨论】:

  • 如果您将 /bin/* 作为参数传递给脚本,您的 shell 会执行通配符(通配符的扩展),并且您的脚本实际上会传递 @987654324 @ 作为多个参数。所以你要么需要做globbing in Python 要么处理多个参数。然后明显地循环不同的文件。

标签: python linux hashlib


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2016-09-23
    相关资源
    最近更新 更多