我遇到了一个问题,内容如下:
我们已经提取了一个外星人的 zip 文件,它是一堆 PNG 文件,但我们认为其中只有一个是有效的。使用 magic byte 来确定它是哪一个。 提示:找到并读取正确的文件以获取标志。
所有png文件都存储在/tmp目录中。经过几次尝试解决这个问题后,我只得到了到目前为止。我的代码运行良好,但为每个文件打印
no
,根据我的代码,没有一个文件是正确的。
这是我到目前为止的代码:
import glob,os
magic_numbers = {'.png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])}
max_read_size = max(len(m) for m in magic_numbers.values()) # get max size of magic numbers of the dict
os.chdir("/tmp")
for x in glob.glob("*.png"):
with open(x, 'rb') as fd:
file_head = fd.read(max_read_size)
if file_head.startswith(magic_numbers['.png']):
print("It's a PNG File")
else:
print("no")
显然我做错了什么,但我不知道它是什么。是循环的问题吗?我该如何使用魔法字节来识别文件?
您的代码需要一些调整,通过在单词
png
前面加上一个点,让文件看起来好像有扩展名。另外,打印file_head
。运行这个:
import glob, os
magic_numbers = {'png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])}
max_read_size = max(len(m) for m in magic_numbers.values()) # get max size of magic numbers of the dict
os.chdir("/tmp")
for x in glob.glob("*png"):
with open(x, 'rb') as fd:
file_head = fd.read()
print(file_head)
if file_head.startswith(magic_numbers['png']):
print("It's a PNG File")
else:
print("no")
它应该打印这样的内容:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82The flag is: 2NECGNQM4GD3QPD' It's a PNG File
你的旗帜可能与我的不同。
干杯!
您可以使用python-magic库。
python-magic 是 libmagic 文件类型识别库的 Python 接口。 libmagic 通过根据预定义的文件类型列表检查文件头来识别文件类型。(来自 pypi)
这个库检查幻数来识别文件类型。
import magic
print(magic.from_file('file.png'))
输出是:
'PNG image data, 2480 x 3437, 8-bit/color RGB, non-interlaced'
玩得开心!
编辑:对于 Windows 使用
pip install python-magic-bin
,Windows 缺少 DLL,因此您必须以这种方式安装它。这是在软件包的安装说明中指定的。