用python写一个校验文件MD5, sha1, sha256, sha512 的脚本
当然可以!下面是一个使用Python编写的脚本,用于校验文件的MD5、SHA-1、SHA-256和SHA-512哈希值。这个脚本会读取指定文件,计算其哈希值,并与提供的哈希值进行比较,以验证文件完整性。
首先,确保你已经安装了Python(建议使用Python 3.x)。然后,你可以使用以下代码:
import hashlibdef calculate_hash(file_path, algorithm):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):return: 文件的哈希值"""hash_func = hashlib.new(algorithm)with open(file_path, 'rb') as f:while chunk := f.read(8192):hash_func.update(chunk)return hash_func.hexdigest()def verify_file(file_path, expected_hashes):"""校验文件的哈希值:param file_path: 文件路径:param expected_hashes: 预期的哈希值字典,键为算法名,值为预期的哈希值:return: 校验结果字典,键为算法名,值为布尔值(True表示校验通过,False表示校验失败)"""results = {}for algorithm, expected_hash in expected_hashes.items():calculated_hash = calculate_hash(file_path, algorithm)results[algorithm] = calculated_hash == expected_hashreturn resultsif __name__ == "__main__":file_path = 'path/to/your/file' # 替换为你的文件路径expected_hashes = {'md5': 'expected_md5_hash', # 替换为你的预期MD5哈希值'sha1': 'expected_sha1_hash', # 替换为你的预期SHA-1哈希值'sha256': 'expected_sha256_hash', # 替换为你的预期SHA-256哈希值'sha512': 'expected_sha512_hash' # 替换为你的预期SHA-512哈希值}verification_results = verify_file(file_path, expected_hashes)for algorithm, result in verification_results.items():print(f"Verification result for {algorithm}: {'Pass' if result else 'Fail'}")
使用步骤:
- 替换文件路径:将
file_path
变量的值替换为你想要校验的文件路径。 - 替换预期哈希值:将
expected_hashes
字典中的值替换为你预期的哈希值。
示例:
假设你有一个文件example.txt
,并且你知道它的预期哈希值,你可以这样设置:
file_path = 'example.txt'
expected_hashes = {'md5': 'd41d8cd98f00b204e9800998ecf8427e', # 这是一个空文件的MD5哈希值'sha1': 'da39a3ee5e6b4b0d3255bfef95601890afd80709', # 这是一个空文件的SHA-1哈希值'sha256': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', # 这是一个空文件的SHA-256哈希值'sha512': 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff4c13a14b95178e3ad8024b8a0147746499075888c9823e37a73303' # 这是一个空文件的SHA-512哈希值
}
运行脚本:
保存脚本到一个Python文件(例如verify_hash.py
),然后在命令行中运行:
python verify_hash.py
脚本将输出每个哈希算法的校验结果,告诉你文件是否通过了校验。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 保持控制台窗口不关闭
为了编写一个Python脚本,该脚本将从控制台输入文件路径,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并且保持控制台窗口不关闭,你可以使用以下代码。这个脚本会在计算完哈希值后等待用户输入,以保持控制台窗口打开状态。
import hashlib
import osdef calculate_hash(file_path, algorithm):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):return: 文件的哈希值"""if not os.path.isfile(file_path):raise FileNotFoundError(f"文件 {file_path} 不存在")hash_func = hashlib.new(algorithm)with open(file_path, 'rb') as f:# 分块读取文件内容并更新哈希值for chunk in iter(lambda: f.read(8192), b""):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径file_path = input("请输入文件路径: ")try:# 计算并打印文件的哈希值md5_hash = calculate_hash(file_path, 'md5')print(f"MD5: {md5_hash}")sha1_hash = calculate_hash(file_path, 'sha1')print(f"SHA-1: {sha1_hash}")sha256_hash = calculate_hash(file_path, 'sha256')print(f"SHA-256: {sha256_hash}")sha512_hash = calculate_hash(file_path, 'sha512')print(f"SHA-512: {sha512_hash}")except FileNotFoundError as e:print(e)# 等待用户输入以保持控制台窗口不关闭input("按任意键退出...")if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker.py
。 -
在命令行中运行该脚本:
python hash_checker.py
-
当脚本提示时,输入你想要校验的文件路径。
-
脚本将计算并打印文件的哈希值。
-
最后,脚本将等待用户按下任意键,然后才会关闭控制台窗口。
注意事项:
- 脚本在尝试打开文件之前会检查文件是否存在,如果文件不存在,将抛出一个
FileNotFoundError
异常,并打印错误信息。 - 脚本使用
iter
和lambda
函数来分块读取文件内容,这有助于处理大文件。 - 脚本最后使用
input("按任意键退出...")
来等待用户输入,从而保持控制台窗口打开状态。用户按下任意键后,脚本将退出。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 将结果输出到指定文件
为了编写一个Python脚本,该脚本将从控制台输入文件路径,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到指定的文件中,你可以使用以下代码。这个脚本会提示用户输入文件路径和输出文件路径,然后计算哈希值并将它们写入到指定的输出文件中。
import hashlib
import osdef calculate_hash(file_path, algorithm):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):return: 文件的哈希值"""if not os.path.isfile(file_path):raise FileNotFoundError(f"文件 {file_path} 不存在")hash_func = hashlib.new(algorithm)with open(file_path, 'rb') as f:# 分块读取文件内容并更新哈希值for chunk in iter(lambda: f.read(8192), b""):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径input_file_path = input("请输入要校验的文件路径: ")# 从控制台输入输出文件路径output_file_path = input("请输入输出文件路径: ")try:# 计算文件的哈希值md5_hash = calculate_hash(input_file_path, 'md5')sha1_hash = calculate_hash(input_file_path, 'sha1')sha256_hash = calculate_hash(input_file_path, 'sha256')sha512_hash = calculate_hash(input_file_path, 'sha512')# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:f.write(f"MD5: {md5_hash}\n")f.write(f"SHA-1: {sha1_hash}\n")f.write(f"SHA-256: {sha256_hash}\n")f.write(f"SHA-512: {sha512_hash}\n")print(f"哈希值已写入到 {output_file_path}")except FileNotFoundError as e:print(e)if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_output.py
。 -
在命令行中运行该脚本:
python hash_checker_output.py
-
当脚本提示时,输入你想要校验的文件路径。
-
接着,输入你想要将哈希值保存到的输出文件路径。
-
脚本将计算文件的哈希值,并将它们写入到指定的输出文件中。
-
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本在尝试打开输入文件之前会检查文件是否存在,如果文件不存在,将抛出一个
FileNotFoundError
异常,并打印错误信息。 - 脚本使用
iter
和lambda
函数来分块读取文件内容,这有助于处理大文件。 - 输出文件将以文本模式打开,并将哈希值逐行写入文件中。如果输出文件已经存在,它将被覆盖。如果你希望追加到现有文件,可以将
open(output_file_path, 'w')
中的'w'
改为'a'
(追加模式)。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 将结果输出到所在文件夹的"hash.txt"文件
为了编写一个Python脚本,该脚本将从控制台输入文件路径,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到与输入文件位于同一文件夹的hash.txt
文件中,你可以使用以下代码。这个脚本会提示用户输入文件路径,然后计算哈希值并将它们写入到同一文件夹下的hash.txt
文件中。
import hashlib
import osdef calculate_hash(file_path, algorithm):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):return: 文件的哈希值"""if not os.path.isfile(file_path):raise FileNotFoundError(f"文件 {file_path} 不存在")hash_func = hashlib.new(algorithm)with open(file_path, 'rb') as f:# 分块读取文件内容并更新哈希值for chunk in iter(lambda: f.read(8192), b""):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径input_file_path = input("请输入要校验的文件路径: ")# 获取输入文件所在的文件夹路径file_dir = os.path.dirname(input_file_path)# 构建输出文件路径output_file_path = os.path.join(file_dir, "hash.txt")try:# 计算文件的哈希值md5_hash = calculate_hash(input_file_path, 'md5')sha1_hash = calculate_hash(input_file_path, 'sha1')sha256_hash = calculate_hash(input_file_path, 'sha256')sha512_hash = calculate_hash(input_file_path, 'sha512')# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:f.write(f"MD5: {md5_hash}\n")f.write(f"SHA-1: {sha1_hash}\n")f.write(f"SHA-256: {sha256_hash}\n")f.write(f"SHA-512: {sha512_hash}\n")print(f"哈希值已写入到 {output_file_path}")except FileNotFoundError as e:print(e)if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_to_file.py
。 -
在命令行中运行该脚本:
python hash_checker_to_file.py
-
当脚本提示时,输入你想要校验的文件路径。
-
脚本将计算文件的哈希值,并将它们写入到与输入文件位于同一文件夹的
hash.txt
文件中。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本在尝试打开输入文件之前会检查文件是否存在,如果文件不存在,将抛出一个
FileNotFoundError
异常,并打印错误信息。 - 脚本使用
os.path.dirname
来获取输入文件所在的文件夹路径,并使用os.path.join
来构建输出文件的完整路径。 - 输出文件将以文本模式打开,并将哈希值逐行写入文件中。如果输出文件已经存在,它将被覆盖。如果你希望追加到现有文件,可以将
open(output_file_path, 'w')
中的'w'
改为'a'
(追加模式),但请注意这可能会导致多个哈希值被追加到同一个文件中,如果脚本被多次运行而不清理旧内容的话。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 将结果输出到所在文件夹的"hash.txt"文件
为了编写一个Python脚本,该脚本将从控制台输入文件路径,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到与输入文件位于同一文件夹的名为hash-{源文件名}.txt
的文件中,你可以使用以下代码。这个脚本会提示用户输入文件路径,然后计算哈希值并将它们写入到以特定格式命名的文本文件中。
import hashlib
import osdef calculate_hash(file_path, algorithm):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):return: 文件的哈希值"""if not os.path.isfile(file_path):raise FileNotFoundError(f"文件 {file_path} 不存在")hash_func = hashlib.new(algorithm)with open(file_path, 'rb') as f:# 分块读取文件内容并更新哈希值for chunk in iter(lambda: f.read(8192), b""):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径input_file_path = input("请输入要校验的文件路径: ")# 获取输入文件的文件名(不包括路径)file_name = os.path.basename(input_file_path)# 获取输入文件所在的文件夹路径file_dir = os.path.dirname(input_file_path)# 构建输出文件路径,格式为 "hash-{源文件名}.txt"output_file_path = os.path.join(file_dir, f"hash-{file_name}.txt")try:# 计算文件的哈希值md5_hash = calculate_hash(input_file_path, 'md5')sha1_hash = calculate_hash(input_file_path, 'sha1')sha256_hash = calculate_hash(input_file_path, 'sha256')sha512_hash = calculate_hash(input_file_path, 'sha512')# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:f.write(f"MD5: {md5_hash}\n")f.write(f"SHA-1: {sha1_hash}\n")f.write(f"SHA-256: {sha256_hash}\n")f.write(f"SHA-512: {sha512_hash}\n")print(f"哈希值已写入到 {output_file_path}")except FileNotFoundError as e:print(e)if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_with_custom_output.py
。 -
在命令行中运行该脚本:
python hash_checker_with_custom_output.py
-
当脚本提示时,输入你想要校验的文件路径。
-
脚本将计算文件的哈希值,并将它们写入到与输入文件位于同一文件夹的名为
hash-{源文件名}.txt
的文件中。例如,如果输入文件是example.txt
,则输出文件将是hash-example.txt
。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本在尝试打开输入文件之前会检查文件是否存在,如果文件不存在,将抛出一个
FileNotFoundError
异常,并打印错误信息。 - 脚本使用
os.path.basename
来获取输入文件的文件名(不包括路径),并使用os.path.dirname
来获取输入文件所在的文件夹路径。然后,它使用这些信息来构建输出文件的完整路径。 - 输出文件将以文本模式打开,并将哈希值逐行写入文件中。如果输出文件已经存在,它将被覆盖。如果你希望追加到现有文件,可以将
open(output_file_path, 'w')
中的'w'
改为'a'
(追加模式),但请注意这可能会导致多个哈希值被追加到同一个文件中,如果脚本被多次运行而不清理旧内容的话。在这个特定脚本中,每次运行都会生成一个新的输出文件,因为文件名包含了源文件名,所以每次都会不同。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 将结果输出到所在文件夹的"hash.txt"文件, 并添加过程进度条
为了编写一个Python脚本,该脚本将从控制台输入文件路径,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到与输入文件位于同一文件夹的名为hash.txt
的文件中,同时添加过程进度条,你可以使用以下代码。这个脚本使用了tqdm
库来显示进度条,你需要先安装这个库(如果还没有安装的话):
pip install tqdm
然后,你可以使用以下Python脚本来实现所需的功能:
import hashlib
import os
from tqdm import tqdmdef calculate_hash(file_path, algorithm, chunk_size=8192):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):param chunk_size: 每次读取的字节数:return: 文件的哈希值"""hash_func = hashlib.new(algorithm)file_size = os.path.getsize(file_path) # 获取文件大小with open(file_path, 'rb') as f:# 使用tqdm显示进度条for chunk in tqdm(iter(lambda: f.read(chunk_size), b""), total=file_size // chunk_size + (file_size % chunk_size > 0), unit='B', ncols=100, desc=f"计算 {algorithm.upper()} 哈希"):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径input_file_path = input("请输入要校验的文件路径: ")# 获取输入文件所在的文件夹路径file_dir = os.path.dirname(input_file_path)# 构建输出文件路径,固定为 "hash.txt"output_file_path = os.path.join(file_dir, "hash.txt")try:# 计算文件的哈希值md5_hash = calculate_hash(input_file_path, 'md5')sha1_hash = calculate_hash(input_file_path, 'sha1')sha256_hash = calculate_hash(input_file_path, 'sha256')sha512_hash = calculate_hash(input_file_path, 'sha512')# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:f.write(f"MD5: {md5_hash}\n")f.write(f"SHA-1: {sha1_hash}\n")f.write(f"SHA-256: {sha256_hash}\n")f.write(f"SHA-512: {sha512_hash}\n")print(f"哈希值已写入到 {output_file_path}")except FileNotFoundError:print(f"文件 {input_file_path} 不存在")except Exception as e:print(f"发生错误: {e}")if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_with_progress.py
。 -
在命令行中运行该脚本:
python hash_checker_with_progress.py
-
当脚本提示时,输入你想要校验的文件路径。
-
脚本将计算文件的哈希值,并在控制台显示进度条。进度条将显示当前正在计算的哈希算法(MD5、SHA-1、SHA-256、SHA-512)的进度。
-
计算完成后,脚本将哈希值写入到与输入文件位于同一文件夹的名为
hash.txt
的文件中。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本使用
os.path.getsize
来获取文件大小,以便为进度条设置总进度。如果文件非常大,这个操作可能会稍微增加一些开销,但通常是可以接受的。 - 脚本中的
tqdm
库用于显示进度条。进度条将显示当前读取的字节数(以字节为单位),并且会根据文件大小和块大小自动调整总步数。 - 如果文件不存在,脚本将捕获
FileNotFoundError
异常并打印错误信息。对于其他类型的异常,脚本将捕获并打印一般的错误信息。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 将结果输出到所在文件夹的 "hash-{源文件名}.txt"文件, 并添加过程进度条
以下是一个Python脚本,该脚本会从控制台接收文件路径作为输入,计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到与源文件位于同一文件夹的名为hash-{源文件名}.txt
的文件中。同时,该脚本在读取文件时会显示一个进度条。
import hashlib
import os
from tqdm import tqdmdef calculate_hash(file_path, algorithm, chunk_size=8192):"""计算文件的哈希值:param file_path: 文件路径:param algorithm: 哈希算法('md5', 'sha1', 'sha256', 'sha512'):param chunk_size: 每次读取的字节数:return: 文件的哈希值"""hash_func = hashlib.new(algorithm)file_size = os.path.getsize(file_path) # 获取文件大小with open(file_path, 'rb') as f:# 使用tqdm显示进度条for chunk in tqdm(iter(lambda: f.read(chunk_size), b''), total=file_size, unit='B', ncols=100, desc=f"计算 {algorithm.upper()} 哈希"):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径input_file_path = input("请输入要校验的文件路径: ")# 检查文件是否存在if not os.path.isfile(input_file_path):print(f"文件 {input_file_path} 不存在")return# 获取文件名(不包括路径)file_name = os.path.basename(input_file_path)# 构建输出文件路径output_file_name = f"hash-{file_name}.txt"output_file_path = os.path.join(os.path.dirname(input_file_path), output_file_name)# 计算文件的哈希值md5_hash = calculate_hash(input_file_path, 'md5')sha1_hash = calculate_hash(input_file_path, 'sha1')sha256_hash = calculate_hash(input_file_path, 'sha256')sha512_hash = calculate_hash(input_file_path, 'sha512')# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:f.write(f"MD5: {md5_hash}\n")f.write(f"SHA-1: {sha1_hash}\n")f.write(f"SHA-256: {sha256_hash}\n")f.write(f"SHA-512: {sha512_hash}\n")print(f"哈希值已写入到 {output_file_path}")if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_with_progress.py
。 -
在命令行中运行该脚本:
python hash_checker_with_progress.py
-
当脚本提示时,输入你想要校验的文件路径。
-
脚本将计算文件的哈希值,并在控制台显示进度条。进度条将显示当前正在计算的哈希算法(MD5、SHA-1、SHA-256、SHA-512)的进度。
-
计算完成后,脚本将哈希值写入到与输入文件位于同一文件夹的名为
hash-{源文件名}.txt
的文件中,其中{源文件名}
是输入文件的名称(不包括路径)。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本使用
os.path.getsize
来获取文件大小,以便为进度条设置总进度。如果文件非常大或位于慢速存储介质上,这个操作可能会稍微增加一些开销,但通常是可以接受的。 - 脚本中的
tqdm
库用于显示进度条。进度条将显示当前读取的字节数(以字节为单位),并且会根据文件大小和块大小自动调整总步数。 - 如果文件不存在,脚本将捕获异常并打印错误信息。
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 去除文件路径的引号, 将结果输出到所在文件夹的 "hash-{源文件名}.txt"文件, 并添加过程进度条
以下是一个Python脚本,它实现了从控制台输入文件路径(自动去除路径引号),计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果输出到与源文件位于同一文件夹的名为hash-{源文件名}.txt
的文件中。同时,该脚本在读取文件时会显示一个进度条。
import hashlib
import os
from tqdm import tqdm
import redef strip_quotes(input_str):"""去除字符串两侧的引号"""return re.sub(r'^["\'](.*?)["\']$', r'\1', input_str)def calculate_hash(file_path, algorithm, chunk_size=8192):"""计算文件的哈希值"""hash_func = hashlib.new(algorithm)total_size = os.path.getsize(file_path)with open(file_path, 'rb') as f:for chunk in tqdm(iter(lambda: f.read(chunk_size), b''), total=total_size, unit='B', ncols=100, desc=f"计算 {algorithm.upper()}"):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径,并去除可能的引号input_file_path = strip_quotes(input("请输入要校验的文件路径(可带引号): "))# 检查文件是否存在if not os.path.isfile(input_file_path):print(f"文件 {input_file_path} 不存在")return# 获取文件名(不包括路径)file_name = os.path.basename(input_file_path)# 构建输出文件路径output_file_name = f"hash-{file_name}.txt"output_file_path = os.path.join(os.path.dirname(input_file_path), output_file_name)# 计算文件的哈希值hashes = {'MD5': calculate_hash(input_file_path, 'md5'),'SHA-1': calculate_hash(input_file_path, 'sha1'),'SHA-256': calculate_hash(input_file_path, 'sha256'),'SHA-512': calculate_hash(input_file_path, 'sha512')}# 将哈希值写入到输出文件中with open(output_file_path, 'w') as f:for algorithm, hash_value in hashes.items():f.write(f"{algorithm}: {hash_value}\n")print(f"哈希值已写入到 {output_file_path}")if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker.py
。 -
在命令行中运行该脚本:
python hash_checker.py
-
当脚本提示时,输入你想要校验的文件路径。你可以输入带引号的路径(例如
"C:\path\to\file.txt"
或'C:\path\to\file.txt'
),脚本会自动去除引号。 -
脚本将计算文件的哈希值,并在控制台显示进度条。进度条会显示当前正在计算的哈希算法的进度。
-
计算完成后,脚本将哈希值写入到与输入文件位于同一文件夹的名为
hash-{源文件名}.txt
的文件中,其中{源文件名}
是输入文件的名称(不包括路径)。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
注意事项:
- 脚本使用正则表达式
re.sub
来去除输入路径两侧的引号(如果有的话)。 - 脚本中的
tqdm
库用于显示进度条。进度条会根据文件大小和块大小自动调整。 - 如果文件不存在,脚本将打印错误信息并退出。
豆包:
import hashlib
import os
import re
import time
from tqdm import tqdmdef calculate_hashes(file_path):hashes = {}with open(file_path, 'rb') as file:total_size = os.path.getsize(file_path)progress = tqdm(total=total_size, unit='B', unit_scale=True)for chunk in iter(lambda: file.read(4096), b''):progress.update(len(chunk))hashes['MD5'] = hashlib.md5(chunk).hexdigest()hashes['SHA1'] = hashlib.sha1(chunk).hexdigest()hashes['SHA256'] = hashlib.sha256(chunk).hexdigest()hashes['SHA512'] = hashlib.sha512(chunk).hexdigest()return hashesdef save_hashes(hashes, file_path):file_name = os.path.splitext(os.path.basename(file_path))[0]output_file = f"hash-{file_name}.txt"with open(output_file, 'w') as file:for key, value in hashes.items():file.write(f"{key}: {value}\n")if __name__ == '__main__':file_path = input("请输入文件路径: ").strip("\"")hashes = calculate_hashes(file_path)save_hashes(hashes, file_path)
用python写一个校验文件MD5, sha1, sha256, sha512 的脚本, 要求从控制台输入文件路径, 去除文件路径的引号, 显示进度条, 将结果输出到所在文件夹的 "hash-{源文件名}.txt"文件, 内容分大小写各保存一份
以下是一个Python脚本,它实现了从控制台输入文件路径(自动去除路径引号),计算文件的MD5、SHA-1、SHA-256和SHA-512哈希值,并将结果(大小写各一份)输出到与源文件位于同一文件夹的名为hash-{源文件名}.txt
的文件中。同时,该脚本在读取文件时会显示一个进度条。
import hashlib
import os
from tqdm import tqdm
import redef strip_quotes(input_str):"""去除字符串两侧的引号"""return re.sub(r'^["\'](.*?)["\']$', r'\1', input_str)def calculate_hash(file_path, algorithm, chunk_size=8192):"""计算文件的哈希值"""hash_func = hashlib.new(algorithm)total_size = os.path.getsize(file_path)with open(file_path, 'rb') as f:for chunk in tqdm(iter(lambda: f.read(chunk_size), b''), total=total_size, unit='B', ncols=100, desc=f"计算 {algorithm.upper()}"):hash_func.update(chunk)return hash_func.hexdigest()def main():# 从控制台输入文件路径,并去除可能的引号input_file_path = strip_quotes(input("请输入要校验的文件路径(可带引号): "))# 检查文件是否存在if not os.path.isfile(input_file_path):print(f"文件 {input_file_path} 不存在")return# 获取文件名(不包括路径)file_name = os.path.basename(input_file_path)# 构建输出文件路径output_file_name = f"hash-{file_name}.txt"output_file_path = os.path.join(os.path.dirname(input_file_path), output_file_name)# 计算文件的哈希值hashes = {'MD5': calculate_hash(input_file_path, 'md5'),'SHA-1': calculate_hash(input_file_path, 'sha1'),'SHA-256': calculate_hash(input_file_path, 'sha256'),'SHA-512': calculate_hash(input_file_path, 'sha512')}# 准备输出内容,大小写各一份output_content_lower = ""output_content_upper = ""for algorithm, hash_value in hashes.items():output_content_lower += f"{algorithm.lower()}: {hash_value.lower()}\n"output_content_upper += f"{algorithm.upper()}: {hash_value.upper()}\n"# 将哈希值写入到输出文件中(大小写各一份)with open(output_file_path, 'w') as f:f.write(output_content_lower)f.write("\n") # 添加一个空行作为分隔f.write(output_content_upper)print(f"哈希值(大小写各一份)已写入到 {output_file_path}")if __name__ == "__main__":main()
使用步骤:
-
将上述代码保存到一个Python文件中,例如
hash_checker_case_sensitive.py
。 -
在命令行中运行该脚本:
python hash_checker_case_sensitive.py
-
当脚本提示时,输入你想要校验的文件路径。你可以输入带引号的路径(例如
"C:\path\to\file.txt"
或'C:\path\to\file.txt'
),脚本会自动去除引号。 -
脚本将计算文件的哈希值,并在控制台显示进度条。进度条会显示当前正在计算的哈希算法的进度。
-
计算完成后,脚本将哈希值(大小写各一份)写入到与输入文件位于同一文件夹的名为
hash-{源文件名}.txt
的文件中,其中{源文件名}
是输入文件的名称(不包括路径)。文件内容将首先列出所有哈希值的小写形式,然后是一个空行,接着是所有哈希值的大写形式。 -
最后,脚本将打印一条消息,告知用户哈希值已写入到指定的输出文件中。
豆包
import hashlib
import os
import re
import time
from tqdm import tqdmdef calculate_hashes(file_path):hashes = {}with open(file_path, 'rb') as file:total_size = os.path.getsize(file_path)progress = tqdm(total=total_size, unit='B', unit_scale=True)for chunk in iter(lambda: file.read(4096), b''):progress.update(len(chunk))hashes['MD5'] = hashlib.md5(chunk).hexdigest()hashes['SHA1'] = hashlib.sha1(chunk).hexdigest()hashes['SHA256'] = hashlib.sha256(chunk).hexdigest()hashes['SHA512'] = hashlib.sha512(chunk).hexdigest()return hashesdef save_hashes(hashes, file_path):file_name = os.path.splitext(os.path.basename(file_path))[0]output_file = f"hash-{file_name}.txt"with open(output_file, 'w') as file:for key, value in hashes.items():file.write(f"{key}: {value.upper()}\n")file.write(f"{key}: {value.lower()}\n")if __name__ == '__main__':file_path = input("请输入文件路径: ").strip("\"")hashes = calculate_hashes(file_path)save_hashes(hashes, file_path)
c知道
你可以使用Python的hashlib
库来计算文件的MD5、SHA1、SHA256和SHA512哈希值,并结合argparse
模块处理命令行参数。下面是一个简单的脚本示例:
import hashlib
import argparse
from tqdm import tqdmdef hash_file(file_path):# 提取文件名file_name = file_path.split('/')[-1]# 创建四个哈希函数对象md5_hash = hashlib.md5()sha1_hash = hashlib.sha1()sha256_hash = hashlib.sha256()sha512_hash = hashlib.sha512()with open(file_path, 'rb') as f:for chunk in iter(lambda: f.read(4096), b''):for hash_obj in (md5_hash, sha1_hash, sha256_hash, sha512_hash):hash_obj.update(chunk)hashes_dict = {'md5': md5_hash.hexdigest(),'sha1': sha1_hash.hexdigest(),'sha256': sha256_hash.hexdigest(),'sha512': sha512_hash.hexdigest()}return file_name, hashes_dictdef main():parser = argparse.ArgumentParser(description='Calculate and save file hashes.')parser.add_argument('file', type=str, help='Path to the file')args = parser.parse_args()file_path = args.file.strip('"')if not file_path.endswith('.txt'): # 检查是否需要处理.txt文件file_path += '.txt'# 输出目录output_dir = '/'.join(file_path.split('/')[:-1])output_file = 'hash-' + file_path.split('/')[-1]output_path = '{}/{}'.format(output_dir, output_file)with open(output_path, 'w') as output_f:for name, hash_value in hash_file(file_path).items():output_f.write(f'{name}: {hash_value}\n')print(f'Hashes saved to: {output_path}')if __name__ == "__main__":main()
import hashlib
import os
from tqdm import tqdmdef calculate_hash(file_path):file_name = os.path.basename(file_path)with open(file_path, 'rb') as f:hash_dict = {'md5': hashlib.md5(),'sha1': hashlib.sha1(),'sha256': hashlib.sha256(),'sha512': hashlib.sha512()}# 使用循环遍历文件内容,更新哈希值for chunk in iter(lambda: f.read(4096), b''):for algo, hash_obj in hash_dict.items():hash_obj.update(chunk)results = {algo: hash_obj.hexdigest().lower() for algo, hash_obj in hash_dict.items()}return file_name, resultsdef save_hashes_to_files(hash_results, file_folder):for algo, hash_value in hash_results.items():output_file = os.path.join(file_folder, f"hash-{file_name}.{algo.lower()}.txt")with open(output_file, 'w') as out:out.write(hash_value)if __name__ == "__main__":try:file_path = input("请输入文件路径(去除引号):").strip('"')file_folder = os.path.dirname(file_path) # 获取文件所在的目录if not os.path.isfile(file_path):print("无效的文件路径。")exit()file_name, hash_values = calculate_hash(file_path)save_hashes_to_files(hash_values, file_folder)print(f"{file_name}的哈希值已成功保存至对应文件夹。")except Exception as e:print(f"遇到错误:{e}")#