Python3 脚本:读取 JSON 文件,下载并校验文件哈希

本脚本使用 Python3 读取 JSON 文件,解析文件信息,并从指定 URL 下载文件,最后校验文件哈希值。

import json
import requests
import hashlib

# 读取 JSON 文件
with open('input.json', 'r') as f:
    data = json.load(f)

disk_size = int(data['diskSize'])  # 磁盘大小
files = data['files']  # 文件列表

for file in files:
    path = file['path']
    name = file['name']
    file_type = file['type']
    ver = file['ver']
    date = file['date']
    time = file['time']
    size = int(file['size'])
    hash_value = file['hash']
    crc = file['crc']

    # 判断磁盘空间是否充足
    if size > disk_size:
        print(f'{name} 磁盘空间不足')
        continue

    # 下载文件
    url = f'https://example.com{path}{name}.{file_type}'
    response = requests.get(url)
    if response.status_code != 200:
        print(f'{name} 下载失败')
        continue

    # 保存文件
    with open(f'{path[1:]}{name}.{file_type}', 'wb') as f:
        f.write(response.content)

    # 校验哈希值
    if hash_value:
        with open(f'{path[1:]}{name}.{file_type}', 'rb') as f:
            md5 = hashlib.md5()
            md5.update(f.read())
            if hash_value != md5.hexdigest().upper():
                print(f'{name} 哈希校验失败')
                continue

    print(f'{name} 下载成功')

input.json 文件格式示例:

{
    'diskSize': '111860615',
    'files': [
        {
            'path': '/character/',
            'name': 'chr_katyusha_kuromorimine_1_5',
            'type': 'unity3d',
            'ver': 911160752,
            'date': 211116,
            'time': 123248,
            'size': 323212,
            'hash': 'B4CAA742CBBF920295F9A5B02C787C6C',
            'crc': '3814598405'
        },
        {
            'path': '/mapdata/',
            'name': 'pos2014503',
            'type': 'bytes',
            'ver': 410191219,
            'date': 161019,
            'time': 201938,
            'size': 177,
            'hash': 'C89AA91C72C6683985C1B6DBF9831E34',
            'crc': ''
        }
    ]
}

脚本功能:

  1. 读取 input.json 文件,获取文件信息,包括路径、文件名、文件类型、版本、大小、哈希值等。
  2. 判断磁盘空间是否足够。
  3. 从指定 URL 下载文件。
  4. 将文件保存到当前目录。
  5. 校验文件哈希值,确保下载文件完整性。

使用方法:

  1. 将 input.json 文件放在与脚本相同的目录下。
  2. 修改 https://example.com 为实际的下载地址。
  3. 运行脚本。

注意:

  1. 脚本中的 diskSize 是指当前目录的剩余空间大小,请根据实际情况调整。
  2. 脚本使用 hashlib 模块校验文件哈希值,确保下载的文件与 input.json 文件中记录的哈希值一致。
  3. 脚本中的 example.com 仅为示例,请替换为真实的下载地址。
  4. 脚本会将下载的文件保存到当前目录下,请确保当前目录有足够的存储空间。
  5. 脚本假设 input.json 文件中的哈希值是 MD5 值,如果您使用其他哈希算法,需要修改脚本中的 hashlib.md5() 为对应的哈希算法。
Python3 脚本:读取 JSON 文件,下载并校验文件哈希

原文地址: https://www.cveoy.top/t/topic/npqu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录