python-3.x之在二进制文件中搜索所有出现的字节串
Demo
阅读:20
2024-12-31 21:38:35
评论:0
我正在编写一个 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.
当 find 无法找到子字符串时,它将返回 -1 但在
if
中声明
-1
转换为
true
并且您的代码已执行。将条件重写为
if search != -1:
它应该开始工作。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。