批量获取文件的摘要(md5、sha1、sha256)升级V-2

仲孙绍元
2023-12-01

0x01 功能

批量获取文件摘要,版本一:https://blog.csdn.net/weixin_40950781/article/details/103707641

刚写的工具,拿去让同事用,得到的结果是:

	Q1:  你这工具不好用啊,文件夹中嵌套文件夹,直接就不行了;
	
	Q2:  绝对路径下就凉凉了;
	
	Q3:  每个可视化界面也叫工具???
	
	Q4:  再添加个供能如何,将文件重命名为MD5+文件名
	
	Q5: 给你提要求的感觉真好

0x02 升级版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/12/28/028 0:07
# @Author  : H
# @File    : getHash.py

import os
import sys
import hashlib
import shutil

def getHash(filename, filepath):
    datas = {}  # 结果存为json,以便后需
    f = open(filepath, "rb")
    rb = f.read()
    data = {'MD5': hashlib.md5(rb).hexdigest(),
            'SHA1': hashlib.sha1(rb).hexdigest(),
            'SHA256': hashlib.sha256(rb).hexdigest()}
    newname = data['MD5'] + '-' + filename
    newname = filepath.replace(filename,newname)
    datas[filename] = data
    f.close()
    # shutil.copyfile(filepath, newname) #重命名并保存原文件

    os.rename(filepath,newname) # 直接重命名

    with open(filepath.replace(filename, "") + "hash.txt", "a", encoding="utf-8")as f:
        f.writelines("filename:\t" + filename + "\n")
        print("[+]succeed get the teatures of " + filename)
        for key, value in datas[filename].items():
            f.writelines(key + ":\t" + value + "\n")
        f.writelines("\n")


def func(path):
    if ":" in path:
        # 如果使用的是绝对路径
        if os.path.isdir(path):
            # 如果绝对路径下的文件夹
            for i in os.listdir(path):  # i文件名
                path2 = os.path.join(path, i)  # 拼接绝对路径
                if os.path.isdir(path2):  # 判断如果是文件夹,调用本身
                    func(path2)
                else:
                    getHash(i, path2)

        elif os.path.isfile(path):
            # 如果绝对路径下的文件
            getHash(path.split("\\")[-1],path)
        else:
            print("file or path don\'t exit")
    else:# 若是相对路径
        path = os.getcwd() + "\\" + path
        if os.path.exists(path):
            func(path)
        else:
            print("file or path don\'t exit")


if sys.argv:
    print("""
   _     _      _     _      _     _      _     _      _     _      _     _
  (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)
   / ._. \      / ._. \      / ._. \      / ._. \      / ._. \      / ._. \
 __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)
   || K ||      || I ||      || L ||      || L ||      || E ||      || R ||
 _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._
(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-`\.-.)
 `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'

======  function:  Get hash of file or files in folder ========

=>=>=>=>=>usage :  python getHash.py [当前目录下或者绝对路径下file/dir]     <=<=<=<=<=<=<=<=<=<=
    """)
    if len(sys.argv) == 2:
        func(sys.argv[1])
    else:
        print("[-]Usage errors")

 类似资料: