来自另一个脚本的MD5散列匹配

2024-10-02 00:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我尝试创建一个脚本来执行以下操作:在一个目录中搜索已知的哈希值。这是我的第一个剧本:

在哈希.py在

import hashlib

from functools import partial

#call another python script
execfile("knownHashes.py")

def md5sum(filename):
    with open(filename, mode='rb') as f:
        d = hashlib.md5()
        for buf in iter(partial(f.read, 128), b''):
            d.update(buf)
    return d.hexdigest()
print "Hash of is: "
print(md5sum('photo.jpg'))

if md5List == md5sum:
    print "Match"

在knownHashes.py在

^{pr2}$

现在的问题是,我必须手动输入文件,我想知道它在哪里显示的哈希值照片.jpg. 另外,我还没有得到md5列表工作。在

我希望剧本最终能这样运作:

python hash.py <directory>
1 match 
cookies.jpg matches hash

那么如何让脚本搜索目录而不是手动键入要散列的文件呢?另外,我如何修复md5List,因为这是错误的?在


Tags: pyimport目录脚本filenamepartialmd5hashlib
2条回答

可以使用以下命令获取当前工作目录中的文件列表。从这个目录运行这个脚本。在

import os

#Get list of files in working directory
files_list = os.listdir(os.getcwd())

可以使用for循环遍历列表:

^{pr2}$

正如下面提到的春分点,也可以使用^{}。在

简单的小要点可以解决你的大部分问题。如果你不喜欢使用OOP来解决这个问题,这是可以理解的,但是我相信所有重要的概念部分都是以一种非常简洁的方式呈现的。如果你有任何问题请告诉我。在

class PyGrep:

    def __init__(self, directory):
        self.directory = directory

    def grab_all_files_with_ending(self, file_ending):
        """Will return absolute paths to all files with given file ending in self.directory"""
        walk_results = os.walk(self.directory)
        file_check = lambda walk: len(walk[2]) > 0
        ending_prelim = lambda walk: file_ending in " ".join(walk[2])
        relevant_results = (entry for entry in walk_results if file_check(entry) and ending_prelim(entry))
        return (self.grab_files_from_os_walk(result, file_ending) for result in relevant_results)

    def grab_files_from_os_walk(self, os_walk_tuple, file_ending):
        format_check = lambda file_name: file_ending in file_name
        directory, subfolders, file_paths = os_walk_tuple
        return [os.path.join(directory, file_path) for file_path in file_paths if format_check(file_path)]

相关问题 更多 >

    热门问题