搜索二进制文件中所有出现的字节串

Searching for all Occurance of Byte Strings in Binary File

我正在编写一个 python 脚本来在一个大型二进制文件中搜索几个不同的字节字符串,到目前为止它运行良好,但是我遇到了一些异常情况。这是我到目前为止所做的:

for i in range(0, fileSizeBytes):
        data.seek(readOffsetIndex, 0)                                   # Change the file index to last search. 
        print('Starting Read at DEC: %s' % str(readOffsetIndex))
        print('Starting Read at HEX: %s' % str(hex(readOffsetIndex)))
        byte = data.read()                                              # Read the file starting at the new index
        search = byte.find(b'\x00\x00\x00\xbb')                       # Search for this string of bytes

        if search:
            byteOffset = (byteOffset + (busWidth+4))
            startOffset = str(hex(byteOffset-4))
            readOffsetIndex = byteOffset
            print('String Found Starting at: ' + startOffset)
            print('READ SET TO: %s' % str(readOffsetIndex))
            print('READ SET TO: %s' % str(hex(readOffsetIndex)))
            print('---------------------------------------------------')
            csvWriter.writerow(['Bus Width', str(startOffset), str(hex(readOffsetIndex)), grabData(byteOffset-4)])

        if (readOffsetIndex >= fileSizeBytes):                          # Check bounds of file size to kill loop
            csvFile.close()
            break

它试图找到的唯一查询是:search = byte.find(b'\x00\x00\x00\xbb')。当我分析数据时,几条记录是完美的,但当我点击搜索位置 0x189da6b 时,我就疯了。数据输出见下图:

就好像只是停止寻找特定的字符串并开始做自己的事情...关于为什么会发生这种情况的任何想法? CSV 共有 88,900 行,其中约 90 行是有效的搜索字符串,其余是您在数据中看到的 jibbereist。


更新#1:

我找到了一种更好的方法来交互二进制文件并定位字节字符串的所有出现以及所述字节字符串的偏移量。下面是一个方法:

from bitstring import ConstBitStream

def parse(register_name,byte_data):
    fileSizeBytes = os.path.getsize(bin_file)
    fileSizeMegaBytes = GetFileSize(os.path.getsize(bin_file))
    data = open(bin_file, 'rb')

    s = ConstBitStream(filename=bin_file)
    occurances = s.findall(byte_data, bytealigned=True)
    occurances = list(occurances)
    totalOccurances = len(occurances)
    byteOffset = 0                                                      # True start of Byte string 

    for i in range(0, len(occurances)):
        occuranceOffset = (hex(int(occurances[i]/8)))
        s0f0, length, bitdepth, height, width = s.readlist('hex:16, uint:16, uint:8, 2*uint:16')  
        s.bitpos = occurances[i]
        data = s.read('hex:32')      
        print('Address: ' + str(occuranceOffset) + ' Data: ' + str(data))
        csvWriter.writerow([register_name, str(occuranceOffset), str(data)])

来自文档

bytes.find(sub[, start[, end]])

Return the lowest index in the data where the subsequence sub is found... Return -1 if sub is not found.

当查找找不到子字符串时,它将 return -1 但在 if 语句中 -1 被转换为 true 并且您的代码是执行。将条件重写为 if search != -1:,它应该开始工作了。