Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import sys, os, argparse
- import mmap, codecs, re
- import signal
- if os.name != 'posix':
- exit('Platform is not supported')
- # Reset SIGINT handler to default value since Python's
- # handler do not respond to the signal during search
- signal.signal(signal.SIGINT, signal.SIG_DFL)
- def parse_args():
- p = argparse.ArgumentParser(description='Binary file search')
- p.add_argument('pattern', type=str, help='pattern to search for', metavar='PATTERN')
- p.add_argument('file', type=str, help='regular file or block device', metavar='FILE')
- p.add_argument('-r', '--regexp', action='store_true', help='do regexp search instead of fixed string')
- p.add_argument('-i', '--ignore_case', action='store_true', help='do case insensitive search (regexp)')
- p.add_argument('-p', '--print_match', action='store_true', help='print matched substring (regexp)')
- p.add_argument('-o', '--output', type=str, default='/dev/stdout', help='output file (default=stdout)')
- p.add_argument('--license', action='store_true', help='show license')
- if '--license' in sys.argv: print('Public domain') or exit(0)
- a = p.parse_args()
- a.pattern = codecs.escape_decode(a.pattern)[0]
- return a
- def mmap_file(file):
- if os.stat(file).st_mode >> 12 not in (6, 8):
- exit('Only regular files and block devices are supported')
- fd = os.open(file, os.O_RDONLY)
- file_size = os.lseek(fd, 0, os.SEEK_END)
- return mmap.mmap(fd, file_size, prot=mmap.PROT_READ)
- def gen_regex(a, mm):
- flags = re.DOTALL | (a.ignore_case and re.I)
- for mo in re.finditer(a.pattern, mm, flags=flags):
- yield mo.start(), mo.group(0)
- def gen_fixed(a, mm):
- offset = 0
- while (offset := mm.find(a.pattern, offset+1)) >= 0:
- yield offset, None
- def do_all():
- a = parse_args()
- mm = mmap_file(a.file)
- gen = gen_regex if a.regexp else gen_fixed
- f = open(a.output, 'wb')
- print_match = a.regexp and a.print_match
- exit_status = 1
- for offset,match in gen(a, mm):
- f.write(f'@ 0x{offset:010x} ({offset})\n'.encode())
- if print_match:
- f.write(match + b'\n')
- f.flush()
- exit_status = 0
- return exit_status
- exit(do_all())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement