gpt4 book ai didi

python - 在 Python 中检查 tarfile 完整性

转载 作者:行者123 更新时间:2023-11-28 21:24:28 26 4
gpt4 key购买 nike

我正在努力将我的备份脚本从 shell 转换为 Python。我的旧脚本的功能之一是通过执行以下操作检查创建的 tarfile 的完整性:gzip -t。

这在 Python 中似乎有点棘手。

似乎唯一的方法就是读取 tar 文件中的每个压缩 TarInfo 对象。

有没有一种方法可以检查 tarfile 的完整性,而无需将其提取到磁盘或将其保存在内存中(完整)?

freenode 上 #python 上的好人建议我应该逐 block 读取每个 TarInfo 对象,丢弃读取的每个 block 。

我必须承认我不知道如何做到这一点,因为我刚刚开始使用 Python。

假设我有一个 30GB 的 tarfile,其中包含 1kb 到 10GB 的文件...

这是我开始编写的解决方案:

try:
tardude = tarfile.open("zero.tar.gz")
except:
print "There was an error opening tarfile. The file might be corrupt or missing."

for member_info in tardude.getmembers():
try:
check = tardude.extractfile(member_info.name)
except:
print "File: %r is corrupt." % member_info.name

tardude.close()

这段代码远未完成。我不敢在一个巨大的 30GB 的 tar 存档上运行它,因为在某一时刻,check 将是一个 10+GB 的对象(如果我在 tar 存档中有这么大的文件)

奖励:我尝试手动破坏 zero.tar.gz(十六进制编辑器 - 编辑几个字节的中间文件)。第一个 except 没有捕捉到 IOError...这是输出:

Traceback (most recent call last):
File "./test.py", line 31, in <module>
for member_info in tardude.getmembers():
File "/usr/lib/python2.7/tarfile.py", line 1805, in getmembers
self._load() # all members, we first have to
File "/usr/lib/python2.7/tarfile.py", line 2380, in _load
tarinfo = self.next()
File "/usr/lib/python2.7/tarfile.py", line 2315, in next
self.fileobj.seek(self.offset)
File "/usr/lib/python2.7/gzip.py", line 429, in seek
self.read(1024)
File "/usr/lib/python2.7/gzip.py", line 256, in read
self._read(readsize)
File "/usr/lib/python2.7/gzip.py", line 320, in _read
self._read_eof()
File "/usr/lib/python2.7/gzip.py", line 342, in _read_eof
hex(self.crc)))
IOError: CRC check failed 0xe5384b87 != 0xdfe91e1L

最佳答案

只是对 Aya's 的一个小改进answer 使事情变得更加地道(尽管我删除了一些错误检查以使机制更加可见):

BLOCK_SIZE = 1024

with tarfile.open("zero.tar.gz") as tardude:
for member in tardude.getmembers():
with tardude.extractfile(member.name) as target:
for chunk in iter(lambda: target.read(BLOCK_SIZE), b''):
pass

这实际上只是删除了 while 1:(有时被认为是轻微的代码味道)和 if not data: 检查。另请注意,使用 with 将其限制为 Python 2.7+

关于python - 在 Python 中检查 tarfile 完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16013291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com