如何创建大小一致、时间戳可定制且内容不同的文件用于备份测试?
解决方案:生成定制化测试文件(Bash/Python)
针对你的测试需求,以下是直接可用的Bash和Python脚本,无需依赖在线服务即可生成符合要求的测试文件:
Bash 脚本实现
场景1:文件大小相同但时间戳不同
# 生成两个1MB大小、内容不同的文件 dd if=/dev/urandom of=file1 bs=1M count=1 dd if=/dev/urandom of=file2 bs=1M count=1 # 将file2的时间戳修改为1天前(可自定义时间,比如"2023-01-01 10:00") touch -d "1 day ago" file2
验证:用ls -l查看时间戳差异,du -h确认大小一致。
场景2:文件大小相同、内容不同但时间戳相同
# 生成两个1MB大小、内容不同的文件(一个用随机内容,一个用空字节) dd if=/dev/urandom of=fileA bs=1M count=1 dd if=/dev/zero of=fileB bs=1M count=1 # 将fileB的时间戳完全同步为fileA的时间戳 touch -r fileA fileB
验证:用md5sum查看内容差异,ls -l确认时间戳一致。
Python 脚本实现
场景1:文件大小相同但时间戳不同
import os import time def generate_fixed_size_file(filename, size_mb): size_bytes = size_mb * 1024 * 1024 # 写入随机内容确保文件内容不同 with open(filename, 'wb') as f: f.write(os.urandom(size_bytes)) # 生成两个1MB的测试文件 generate_fixed_size_file('test1.txt', 1) generate_fixed_size_file('test2.txt', 1) # 将test2.txt的时间戳设置为3小时前 past_timestamp = time.time() - 3 * 3600 os.utime('test2.txt', (past_timestamp, past_timestamp))
场景2:文件大小相同、内容不同但时间戳相同
import os def generate_fixed_size_file(filename, size_mb, use_zero_content=False): size_bytes = size_mb * 1024 * 1024 with open(filename, 'wb') as f: if use_zero_content: f.write(b'\x00' * size_bytes) else: f.write(os.urandom(size_bytes)) # 生成两个1MB、内容不同的文件 generate_fixed_size_file('testA.txt', 1) generate_fixed_size_file('testB.txt', 1, use_zero_content=True) # 同步testB的时间戳与testA一致 file_a_stat = os.stat('testA.txt') os.utime('testB.txt', (file_a_stat.st_atime, file_a_stat.st_mtime))
测试预期参考
- rsync --checksum:仅通过校验和判断同步,场景2(内容不同、时间戳相同)会触发同步,场景1(时间戳不同、内容相同)不会触发同步。
- aws s3 sync:
- 默认逻辑:基于时间戳+大小判断,场景1会触发同步,场景2不会。
- 加
--size-only:仅校验大小,两个场景都不会触发同步。 - 加
--checksum:基于校验和判断,场景2会触发同步,场景1不会。
内容的提问来源于stack exchange,提问作者Leslie Alldridge
相关产品推荐
相关产品推荐

