import hashlib
import os
import json
from pathlib import Path
# 计算文件的哈希值
def calculate_hash(file_path, hash_algorithm="sha256"):
hash_func = getattr(hashlib, hash_algorithm)() # 获取对应的哈希算法
try:
with open(file_path, 'rb') as file:
while chunk := file.read(8192): # 读取文件的每一部分
hash_func.update(chunk) # 更新哈希值
return hash_func.hexdigest() # 返回文件的哈希值
except Exception as e:
print(f"Error calculating hash for {file_path}: {e}")
return None
# 将哈希值记录到JSON文件中
def update_hash_in_json(file_path, hash_value, hash_algorithm, log_file="hash_log.json"):
# 检查是否已经存在 JSON 文件,若存在则加载现有数据
if os.path.exists(log_file):
with open(log_file, 'r') as f:
log_data = json.load(f)
else:
log_data = []
# 创建新的日志条目
log_entry = {
"file": str(file_path),
"hash_algorithm": hash_algorithm.upper(),
"hash": hash_value
}
# 将新的日志条目添加到现有数据中
log_data.append(log_entry)
# 将所有日志数据写回 JSON 文件
with open(log_file, 'w') as f:
json.dump(log_data, f, indent=4)
print(f"Hash for {file_path} has been updated in the JSON log.")
# 搜索当前脚本所在目录的文件并处理,但排除脚本文件本身
def process_current_directory(hash_algorithm="sha256"):
# 获取当前脚本所在目录
current_directory = Path(__file__).parent
script_name = Path(__file__).name # 获取脚本文件名
print(f"Processing files in directory: {current_directory}")
for file_path in current_directory.rglob("*"): # 遍历当前目录及子目录的所有文件
if file_path.is_file() and file_path.name != script_name: # 排除脚本文件本身
print(f"Processing file: {file_path}")
file_hash = calculate_hash(file_path, hash_algorithm)
if file_hash:
update_hash_in_json(file_path, file_hash, hash_algorithm)
# 主函数
if __name__ == "__main__":
# 处理当前脚本所在目录中的所有文件,排除脚本文件本身
process_current_directory("sha256") # 使用 SHA-256 哈希算法