### Start and Manage Grep Subprocess with Python Source: https://context7.com/pablolec/recoverpy/llms.txt This snippet demonstrates how to initiate a grep process to search a disk partition for a specific string using Python's `subprocess` module and Recoverpy's `thread_factory`. It shows how to read the output line by line, with each line formatted as 'byte_offset:matching_content', and how to terminate the process. ```python from recoverpy.lib.search.thread_factory import start_grep_process from subprocess import Popen # Start grep process to search partition for a string partition = "/dev/sda1" search_string = "lost_data" grep_process: Popen[bytes] = start_grep_process(search_string, partition) # Equivalent to: grep -a -b "lost_data" /dev/sda1 # Read output line by line for line in iter(grep_process.stdout.readline, b""): # Each line format: "byte_offset:matching_content" # Example: "123456789:This line contains lost_data here" print(line.decode("utf-8", errors="ignore")) # Terminate when done grep_process.kill() ``` -------------------------------- ### Get Disk Partitions with Python Source: https://context7.com/pablolec/recoverpy/llms.txt Uses the `get_partitions` function from `recoverpy.lib.lsblk` to retrieve a list of disk partitions. Supports filtering to exclude loop devices and swap partitions. Outputs partition details like name, full path, filesystem type, mount status, and mount point. ```python from recoverpy.lib.lsblk import get_partitions from recoverpy.models.partition import Partition # Get all partitions (unfiltered) all_partitions = get_partitions(filtered=False) # Get filtered partitions (excludes loop devices and swap) partitions = get_partitions(filtered=True) for partition in partitions: print(f"Name: {partition.name}") # e.g., "sda1" print(f"Full path: {partition.get_full_name()}") # e.g., "/dev/sda1" print(f"Filesystem: {partition.fs_type}") # e.g., "ext4" print(f"Mounted: {partition.is_mounted}") # True/False print(f"Mount point: {partition.mount_point}") # e.g., "/home" ``` -------------------------------- ### Run RecoverPy Commands Source: https://context7.com/pablolec/recoverpy/llms.txt Commands to run RecoverPy directly using pipx, uvx, or if installed via pip. Includes an option for enabling debug logging. ```bash sudo pipx run recoverpy sudo uvx recoverpy sudo recoverpy sudo recoverpy --debug ``` -------------------------------- ### Initialize and Run Recoverpy TUI Application Source: https://context7.com/pablolec/recoverpy/llms.txt This example shows how to instantiate and run the main TUI application class, `RecoverpyApp`, from the Recoverpy project. The `RecoverpyApp` class orchestrates the user interface, managing a sequence of screens including parameter input, search results display, block content exploration, and save confirmation. The `run()` method blocks until the application is exited by the user. ```python from recoverpy.ui.app import RecoverpyApp # Create and run the application app = RecoverpyApp() # The app manages these screens: # - "params": Initial screen for partition selection and search input # - "search": Displays grep results as they're found # - "result": Shows block content and allows block navigation # - "save": Confirms save path and saves selected blocks # - "path_edit": Allows editing the save directory # Run the application (blocks until exit) app.run() # Screen flow: # 1. ParamsScreen: User enters search string and selects partition # 2. SearchScreen: Displays matching results in real-time # 3. ResultScreen: User explores block content, navigates adjacent blocks # 4. SaveScreen: User confirms save path and saves recovered data ``` -------------------------------- ### Parse Grep Output Line with GrepResult Model Source: https://context7.com/pablolec/recoverpy/llms.txt This example shows how to use the `GrepResult` class from Recoverpy to parse a raw grep output line. The class extracts the byte offset (used to determine the inode/block number) and the printable content of the line. It also demonstrates generating a CSS class for UI styling and creating a list item representation for TUI display. ```python from recoverpy.models.grep_result import GrepResult # Parse a raw grep result line # Format: "byte_offset:content..." raw_line = "987654321:important data found here with lost_data keyword" result = GrepResult(raw_line) print(f"Inode/Block: {result.inode}") # Extracted from byte offset print(f"Content: {result.line}") # Printable portion of the line print(f"CSS class: {result.css_class}") # For UI styling # Create list item for TUI display result.create_list_item() print(f"List item ID: {result.list_item.id}") # "grep-result-987654321" ``` -------------------------------- ### Manage and Save Recovered Blocks with Saver Class Source: https://context7.com/pablolec/recoverpy/llms.txt This Python snippet illustrates the usage of the `Saver` class for persisting collected disk blocks. It covers setting a custom save path, adding multiple results (which are internally ordered by inode), checking the number of blocks queued for saving, and finally saving the results to a file. The example also shows how to retrieve the path of the last saved file and reset the saver for a new session. ```python from recoverpy.lib.saver import Saver from pathlib import Path saver = Saver() # Set custom save path saver.set_save_path("/home/user/recovered") # Add multiple blocks (blocks are ordered by inode when saved) saver.add_result(inode=1000, result="Content of block 1000...") saver.add_result(inode=1002, result="Content of block 1002...") saver.add_result(inode=1001, result="Content of block 1001...") # Check how many blocks are queued count = saver.get_blocks_to_save_count() print(f"Blocks to save: {count}") # Output: Blocks to save: 3 # Save all results (blocks are ordered by inode: 1000, 1001, 1002) saver.save_results() # Get the path of the last saved file print(f"Saved to: {saver.last_saved_file}") # Output: Saved to: /home/user/recovered/recoverpy-save-2024-01-15-143022 # Reset for new recovery session saver.reset_results() ``` -------------------------------- ### Perform Disk Search with Python Source: https://context7.com/pablolec/recoverpy/llms.txt Utilizes the `SearchEngine` class to perform content-based searches across disk blocks using `grep`. It supports asynchronous operations and provides progress updates. The `SearchParams` model handles search configurations, including multiline searches. ```python import asyncio from recoverpy.lib.search.search_engine import SearchEngine from recoverpy.models.grep_result import GrepResult async def search_disk(): partition = "/dev/sda1" search_string = "important_config_value" # Create search engine instance engine = SearchEngine(partition, search_string) # Access search parameters print(f"Partition: {engine.search_params.partition}") print(f"Block size: {engine.search_params.block_size}") print(f"Is multiline: {engine.search_params.is_multi_line}") # Start the asynchronous search await engine.start_search() # Consume results from the async queue while True: result: GrepResult = await engine.formatted_results_queue.get() print(f"Found at inode {result.inode}: {result.line[:100]}...") # Check progress print(f"Results found: {engine.search_progress.result_count}") print(f"Progress: {engine.search_progress.progress_percent}%") # Stop the search when done engine.stop_search() # asyncio.run(search_disk()) # Run as root ``` -------------------------------- ### Verify System Requirements with Recoverpy Environment Checks Source: https://context7.com/pablolec/recoverpy/llms.txt This Python code snippet demonstrates how to use Recoverpy's environment check utilities to validate system requirements before initiating a data recovery process. It checks for root user privileges, Linux operating system, supported Python version (3.8+), and the presence of essential system dependencies like 'grep', 'dd', 'lsblk', and 'blockdev'. It also includes an optional check for the 'progress' utility for monitoring. ```python from recoverpy.lib.env_check import ( _is_user_root, _is_linux, _is_version_supported, _are_system_dependencies_installed ) from recoverpy.lib.helper import is_dependency_installed # Check if running as root (required for raw disk access) if not _is_user_root(): print("Error: Must run as root (sudo)") # Verify Linux system if not _is_linux(): print("Warning: RecoverPy is designed for Linux only") # Check Python version (3.8+ required) if not _is_version_supported(): print("Error: Python 3.8 or higher required") # Verify all required system utilities are installed if not _are_system_dependencies_installed(): print("Error: Missing dependencies") for dep in ["grep", "dd", "lsblk", "blockdev"]: installed = is_dependency_installed(dep) print(f" {dep}: {'OK' if installed else 'MISSING'}") # Optional: Check for progress monitoring if is_dependency_installed("progress"): print("Progress monitoring available") ``` -------------------------------- ### Python: Programmatic File Recovery Workflow Source: https://context7.com/pablolec/recoverpy/llms.txt This Python script demonstrates a complete data recovery workflow using RecoverPy. It finds a target partition, searches for specific content within that partition, collects matching results, decodes block content, and saves the recovered data. It utilizes asyncio for asynchronous operations and relies on modules like lsblk, SearchEngine, and Saver. ```python import asyncio from recoverpy.lib.lsblk import get_partitions from recoverpy.lib.search.search_engine import SearchEngine from recoverpy.lib.helper import get_dd_output, decode_result from recoverpy.lib.saver import Saver async def recover_lost_file(): # Step 1: Find your partition partitions = get_partitions(filtered=True) for p in partitions: if p.mount_point == "/home": target_partition = p.get_full_name() break # Step 2: Search for content you remember from the lost file engine = SearchEngine(target_partition, "unique string from lost file") await engine.start_search() # Step 3: Collect results saver = Saver() saver.set_save_path("/tmp/recovery") results_collected = 0 while results_collected < 10: # Limit for example try: result = await asyncio.wait_for( engine.formatted_results_queue.get(), timeout=5.0 ) # Step 4: Read full block content block_content = decode_result( get_dd_output( target_partition, engine.search_params.block_size, result.inode ) ) print(f"Found match at block {result.inode}") print(f"Preview: {result.line[:80]}...") # Step 5: Add promising blocks to saver saver.add_result(result.inode, block_content) results_collected += 1 except asyncio.TimeoutError: break # Step 6: Save recovered content engine.stop_search() if saver.get_blocks_to_save_count() > 0: saver.save_results() print(f"Recovered data saved to: {saver.last_saved_file}") # Run with: sudo python script.py # asyncio.run(recover_lost_file()) ``` -------------------------------- ### Detect Partition Block Size with Python Source: https://context7.com/pablolec/recoverpy/llms.txt Retrieves the block size of a specified partition using the `get_block_size` function from `recoverpy.lib.helper`. This function typically utilizes the `blockdev` utility. The output is in bytes. ```python from recoverpy.lib.helper import get_block_size # Get the block size of a partition (typically 4096 bytes) partition = "/dev/sda1" block_size = get_block_size(partition) print(f"Block size: {block_size} bytes") # Output: Block size: 4096 bytes ``` -------------------------------- ### Search Parameters Model in Python Source: https://context7.com/pablolec/recoverpy/llms.txt Defines the `SearchParams` model for configuring search operations in RecoverPy. It supports both single-line and multiline search strings. For multiline searches, it expects a string containing all lines that must be present in a block. ```python from recoverpy.models.search_params import SearchParams # Single line search params = SearchParams("/dev/sda1", "database_password") print(f"Lines to search: {params.searched_lines}") # ['database_password'] print(f"Is multiline: {params.is_multi_line}") # False # Multiline search (finds blocks containing ALL lines) multiline_search = """def important_function(): return secret_value""" params_multi = SearchParams("/dev/sda1", multiline_search) print(f"Lines to search: {params_multi.searched_lines}") ``` -------------------------------- ### Read Disk Blocks with dd in Python Source: https://context7.com/pablolec/recoverpy/llms.txt Reads raw bytes from a specific block of a partition using the `get_dd_output` function from `recoverpy.lib.helper`. It then decodes these bytes into a string using `decode_result` and extracts printable characters with `get_printable`. Requires partition path, block size, and the inode (block number). ```python from recoverpy.lib.helper import get_dd_output, decode_result, get_printable partition = "/dev/sda1" block_size = 4096 inode = 12345 # Block number to read # Read raw bytes from the disk block raw_output = get_dd_output(partition, block_size, inode) # Decode bytes to string (handles encoding errors gracefully) decoded = decode_result(raw_output) # Get printable characters only (removes non-printable chars) printable_content = get_printable(decoded) print(printable_content) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.