Created
January 12, 2025 09:51
-
-
Save SweBarre/b3dc9063515e97ab8aed6e7ecaf5585d to your computer and use it in GitHub Desktop.
search memory used by a process for a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import string | |
from argparse import ArgumentParser | |
def create_parser(args=sys.argv[1:]): | |
parser = ArgumentParser() | |
parser.add_argument("--pid", "-p", type=int, help="the PID number of the process") | |
parser.add_argument("--string", "-s", help="Search string") | |
return parser | |
def search_process_memory(pid, search_string): | |
try: | |
# Open the memory file of the process | |
with open(f"/proc/{pid}/mem", "rb") as mem_file: | |
# Open maps to get memory regions | |
with open(f"/proc/{pid}/maps", "r") as maps_file: | |
# Read memory regions | |
for line in maps_file: | |
# Parse memory region | |
region = line.split() | |
if not "r" in region[1]: # Skip non-readable regions | |
continue | |
# Get start and end addresses | |
addr_range = region[0].split("-") | |
start = int(addr_range[0], 16) | |
end = int(addr_range[1], 16) | |
try: | |
# Seek to the start of the region | |
mem_file.seek(start) | |
# Read the region | |
chunk = mem_file.read(end - start) | |
# Search for the string in the chunk | |
offset = chunk.find(search_string.encode()) | |
if offset != -1: | |
# Found the string, read until unprintable character | |
result = [] | |
pos = offset | |
while pos < len(chunk): | |
char = chunk[pos : pos + 1].decode(errors="ignore") | |
if not char in string.printable: | |
break | |
result.append(char) | |
pos += 1 | |
print( | |
f"Found at offset 0x{start + offset:x}: {''.join(result)}" | |
) | |
except Exception as e: | |
continue # Skip regions that can't be read | |
except PermissionError: | |
print("Error: Permission denied. Try running with sudo.") | |
sys.exit(1) | |
except FileNotFoundError: | |
print(f"Error: Process with PID {pid} not found.") | |
sys.exit(1) | |
def main(): | |
parser = create_parser() | |
args = parser.parse_args() | |
search_process_memory(args.pid, args.string) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment