如何使用python使用magic bytes来识别文件

Lar*_*r21 5 python byte file

我遇到了一个问题,其中指出:

我们已经提取了一个外星人 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")
Run Code Online (Sandbox Code Playgroud)

显然我做错了什么,但我不知道它是什么。是循环的问题吗?我该如何使用魔术字节来识别文件?

Oll*_*lie 3

您的代码需要进行一些调整,通过在单词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")
Run Code Online (Sandbox Code Playgroud)

它应该打印如下内容:

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
Run Code Online (Sandbox Code Playgroud)

你的旗帜可能与我的不同。

干杯!