我正在尝试在充满二进制文件的文件夹中搜索非常特定的字符串。目的是让程序打开每个二进制文件,搜索特定的字符串,然后打印出该字符串所在的文件。
我认为我有一些可以完成的工作,但是还没有完成。我在要搜索的字符串上播放bytes
,但仍然找不到任何内容。我也尝试过struct.uppack
,但这似乎也不起作用。
非常感谢您的帮助。谢谢您的宝贵时间。
代码:
import os
toSearch =bytes("find me","unicode_escape")
folderToSearch = "C:\\dir\\for\\bin\\files"
for root, dirs, files in os.walk(folderToSearch):
for file in files:
if file.endswith(".ROM"):
with open(root+"\\"+file,"rb") as binary_file:
fileContent = binary_file.read()
if fileContent.find(toSearch) != -1:
print(os.path.join(root, file))
答案 0 :(得分:0)
这可以帮助您进行一些调试。 (我还重构了您的代码,使其使用pathlib
而非os
使其更整洁。)
from pathlib import Path
encoding = "unicode_escape"
search_dir = Path("C:\\dir\\for\\bin\\files")
search_bytes = bytes("find me", encoding)
roms = {"match": [], "no_match": []}
for rom_file in search_dir.glob("**/*.ROM"):
with open(rom_file, 'rb') as rom_handle:
rom_contents = rom_handle.read()
match = "match" if (search_bytes in rom_contents) else "no_match"
roms[match].append({
str(rom_file.resolve()): rom_contents
})
如果运行此命令,则可以手动检查读取的字节是否匹配/不匹配。
答案 1 :(得分:0)
我不确定为什么不能使用find()
,但是在我的系统上可以使用以下功能:
import os
toSearch = b"find me"
folderToSearch = "C:\\dir\\for\\bin\\files"
for root, dirs, files in os.walk(folderToSearch):
for file in files:
if file.endswith(".ROM"):
print(f'checking file {file}')
filepath = os.path.join(root, file)
with open(filepath, "rb") as binary_file:
fileContent = binary_file.read()
if toSearch in fileContent:
print(filepath)
print('done')