Skip to content

Instantly share code, notes, and snippets.

@kriander

kriander/fragsearch.py

Last active Jul 29, 2020
Embed
What would you like to do?
Search for binary fragment in source file
#!/usr/bin/env python3
"""Search for binary fragment in a source file."""
import argparse
import numpy as np
def search(fragment, source, tol):
"""Search source for first match of tol percent of the fragment.
Return match tuple: (number of bytes that match fragment, byte
offset in source where match occurs or None)."""
m = len(fragment)
nbyte_min = round(m * tol)
for i in range(len(source) - m + 1):
n = np.sum(fragment == source[i:i+m])
if n > nbyte_min:
return n, i
return 0, None
if __name__ == "__main__":
p = argparse.ArgumentParser(prog="fragsearch.py", description=__doc__)
p.add_argument("-f", dest="fragment", type=str,
help="file containing binary fragment")
p.add_argument("-t", "--tol", dest="tol", type=float, default=0.5,
help="comparison tolerance [0, 1]")
p.add_argument(dest="source", type=str,
help="file to search for fragment")
args = p.parse_args()
fragment = np.fromfile(args.fragment, dtype=np.uint8)
source = np.fromfile(args.source, dtype=np.uint8)
nbyte, offset = search(fragment, source, args.tol)
if nbyte:
print("Position :", offset)
print("{} bytes of {} match".format(nbyte, len(fragment)))
else:
print("No match found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.