Python 스크립트를 사용하여 바이너리 파일의 패턴 검색

Python 스크립트를 사용하여 바이너리 파일의 패턴 검색

패턴과 "마법" 헤더를 사용하여 파티션 덤프(바이너리 파일)에서 구성 섹션의 중복 복사본을 찾고 싶습니다. 구성 섹션은 항상 '0xff'202바이트로 시작하고 그 뒤에 4바이트가 옵니다 '\x00\x00\x23\x27'. 스크립트는 파티션 내 구성의 다양한 복사본을 식별하고 패턴이 시작되는 주소(바이트)를 인쇄해야 합니다. 내 패턴에 맞게 기존 Python 스크립트를 조정했지만 작동하지 않습니다. 바이트가 문자열과 혼합되어 있기 때문에 오류가 발생합니다. 이 스크립트를 수정하는 방법은 무엇입니까?

#!/usr/bin/env python3
import re
import mmap
import sys

magic = '\xff' * 202
pattern = magic + '\x00\x00\x23\x27'

fh = open(sys.argv[1], "r+b")
mf = mmap.mmap(fh.fileno(), 0)
mf.seek(0)
fh.seek(0)
for occurence in re.finditer(pattern, mf):
    print(occurence.start())
mf.close()
fh.close()

실수:

$ ./matcher.py dump.bin
Traceback (most recent call last):
  File "/home/eviecomp/BC2UTILS/dump_previous_profile/./matcher.py", line 13, in <module>
    for occurence in re.finditer(pattern, mf):
  File "/usr/lib/python3.9/re.py", line 248, in finditer
    return _compile(pattern, flags).finditer(string)
TypeError: cannot use a string pattern on a bytes-like object

패턴과 마법:

여기에 이미지 설명을 입력하세요.

답변1

바이트 문자열을 처리하는 것이 가능 하지만 (경고 메시지 텍스트에 주의를 기울이고 대신 re객체를 검색하면 됩니다 ) 여기서는 과도한 것처럼 보입니다.bytesstr

#!/usr/bin/env python3
import mmap
from sys import argv

# NOTE: important to use `b''` literals!
magic = b'\xff' * 202
pattern = magic + b'\x00\x00\x23\x27'


with open(argv[1], "r+b") as fh:
  with mmap.mmap(fh.fileno(), 0) as mm:
    pos = -1
    while -1 != (pos := mm.find(pattern, pos + 1)):
      print(pos)

또는 현대적인 Python의 아름다움을 위해 일치 항목에 "반복자"를 사용할 수도 있습니다.

from mmap import mmap
from typing import Generator
from sys import argv

def positions(mm: mmap, pattern: bytes) -> Generator[int, None, None]:
  pos = -1
  while -1 != (pos := mm.find(pattern, pos + 1)):
    yield pos

pattern = b'\xff' * 202 + b'\x00\x00\x23\x27'

with open(argv[1], "r+b") as lfile:
  with mmap(lfile.fileno(), 0) as mapping:
    all_positions = ", ".join(f"{pos:#0x}" for pos in positions(mapping, pattern))

print(all_positions)

관련 정보