Python 3.x 搜索二进制文件中所有出现的字节字符串
我正在编写一个python脚本,在一个大的二进制文件中搜索几个不同的字节字符串,到目前为止,它工作得很好,但是,我遇到了一点异常。以下是我迄今为止所做的工作:Python 3.x 搜索二进制文件中所有出现的字节字符串,python-3.x,hex,binaryfiles,Python 3.x,Hex,Binaryfiles,我正在编写一个python脚本,在一个大的二进制文件中搜索几个不同的字节字符串,到目前为止,它工作得很好,但是,我遇到了一点异常。以下是我迄今为止所做的工作: for i in range(0, fileSizeBytes): data.seek(readOffsetIndex, 0) # Change the file index to last search. print('Starting
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总共有88900行,其中大约90行是有效的搜索字符串,其余的是您在数据中看到的JibberList
更新#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)])
从文件中 字节。查找(子[,开始[,结束]]) 返回找到子序列子序列的数据中的最低索引。。。如果未找到子项,则返回-1
当find无法定位子字符串时,它将返回-1,但在
if
语句中,-1
将转换为true
,并执行代码。如果搜索!=-1:并且它应该开始工作。这肯定会起作用。非常感谢。我确实找到了另一种方法,并在更新中列出了我的解决方案。