CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-command-runner

Platform agnostic command and shell execution tool with timeout handling, live output capture, and UAC/sudo privilege elevation

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

privilege-elevation.mddocs/

Privilege Elevation

Cross-platform privilege elevation functionality supporting UAC on Windows and sudo on Unix systems. Compatible with various Python packaging formats including CPython, Nuitka, PyInstaller, and frozen executables.

Capabilities

Main Elevation Function

Automatically elevates privileges and executes functions with administrative rights, handling platform detection and execution environment detection transparently.

def elevate(callable_function, *args, **kwargs):
    """
    Elevate privileges and execute function with administrative rights.
    
    Automatically detects the current platform and execution environment (CPython,
    Nuitka, PyInstaller, etc.) and uses the appropriate elevation method. On Windows,
    triggers UAC prompt and re-executes with administrative privileges. On Unix systems,
    uses sudo to gain root privileges. Exits the current process after elevation.
    
    Args:
        callable_function: Function to execute with elevated privileges
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function
        
    Returns:
        Does not return - calls sys.exit() with child process exit code
        
    Raises:
        SystemExit: Always exits after elevation attempt
        EnvironmentError: If platform is unsupported or elevation unavailable
        
    Examples:
        Simple elevation:
        >>> def admin_task():
        ...     print("Running with admin privileges")
        ...     # Perform administrative operations
        >>> 
        >>> if __name__ == '__main__':
        ...     elevate(admin_task)
        
        Elevation with arguments:
        >>> def install_service(service_name, service_path):
        ...     # Install system service with admin rights
        ...     pass
        >>> 
        >>> if __name__ == '__main__':
        ...     elevate(install_service, "MyService", "/opt/myapp/service")
        
        Conditional elevation:
        >>> def main():
        ...     if not is_admin():
        ...         print("Requesting administrator privileges...")
        ...         elevate(main)
        ...     else:
        ...         print("Running with admin privileges")
        ...         # Perform administrative tasks
        >>> 
        >>> if __name__ == '__main__':
        ...     main()
        
    Platform Behavior:
        Windows: Triggers UAC elevation dialog, re-executes script with elevated token
        Unix/Linux: Uses sudo to re-execute script with root privileges
        macOS: Uses sudo with appropriate path handling
        
    Execution Environment Support:
        CPython: Re-executes Python interpreter with script
        Nuitka: Re-executes compiled binary
        PyInstaller: Re-executes frozen executable
        cx_freeze: Re-executes frozen executable
        py2exe: Re-executes frozen executable
        
    Security Notes:
        - Always validates elevation success before performing privileged operations  
        - Preserves command-line arguments across elevation
        - Handles quoted arguments correctly to prevent injection attacks
        - Uses absolute paths to prevent PATH-based attacks
    """

Privilege Detection

Check current privilege level to determine if elevation is needed.

def is_admin():
    """
    Check if current process has administrative privileges.
    
    Tests whether the current process is running with administrative/root privileges
    using platform-appropriate methods. Does not require external dependencies.
    
    Returns:
        bool: True if process has administrative privileges, False otherwise
        
    Raises:
        EnvironmentError: If platform is unsupported for privilege detection
        
    Examples:
        Check before privileged operations:
        >>> if is_admin():
        ...     print("Already running as administrator")
        ...     perform_admin_tasks()
        ... else:
        ...     print("Need to elevate privileges")
        ...     elevate(perform_admin_tasks)
        
        Conditional feature availability:
        >>> def get_available_features():
        ...     features = ['basic_features']
        ...     if is_admin():
        ...         features.extend(['admin_features', 'system_config'])
        ...     return features
        
    Platform Implementation:
        Windows: Uses IsUserAnAdmin() from win32com.shell.shell
        Unix/Linux: Checks if os.getuid() == 0 (root user)
        macOS: Uses Unix method (root user check)
        
    Performance Notes:
        - Fast check using native platform APIs
        - No network or file system access required
        - Safe to call frequently without performance impact
    """

Utility Functions

Helper functions for elevation system implementation and debugging.

def get_absolute_path(executable):
    """
    Find absolute path of executable in system PATH.
    
    Searches for the specified executable in system PATH directories and returns
    the absolute path. Used internally for finding sudo on Unix systems and
    available as a public utility function.
    
    Args:
        executable (str): Name of executable to find (e.g., "sudo", "python")
        
    Returns:
        str: Absolute path to executable, or None if not found
        
    Examples:
        Find sudo executable:
        >>> from command_runner.elevate import get_absolute_path
        >>> sudo_path = get_absolute_path("sudo")
        >>> if sudo_path:
        ...     print(f"sudo found at: {sudo_path}")
        ... else:
        ...     print("sudo not found in PATH")
        
        Find Python interpreter:
        >>> python_path = get_absolute_path("python3")
        >>> print(f"Python 3 location: {python_path}")
        
        Verify tool availability:
        >>> if get_absolute_path("docker"):
        ...     print("Docker is available")
        ... else:
        ...     print("Docker not found in PATH")
        
    Implementation:
        Uses command_runner to execute 'type -p' command for reliable path detection
        Falls back to PATH environment variable parsing on failure
        Validates file existence before returning path
        Cross-platform compatible (Windows uses semicolon, Unix uses colon PATH separator)
    """

Platform-Specific Implementation Details

Windows UAC Elevation

Windows elevation uses the ShellExecuteEx API with the "runas" verb to trigger UAC:

# Internal Windows elevation process
def _windows_runner(runner, arguments):
    """
    Execute elevated process on Windows using UAC.
    
    Uses ShellExecuteEx with runas verb to trigger User Account Control
    elevation dialog. Waits for child process completion and returns exit code.
    """

Windows Dependencies:

  • win32event: Process monitoring
  • win32process: Process management
  • win32com.shell.shell: UAC elevation APIs

Windows Behavior:

  • Displays UAC elevation prompt to user
  • Re-executes current script/executable with elevated token
  • Preserves command-line arguments with proper quoting
  • Waits for elevated process completion
  • Returns child process exit code

Unix Sudo Elevation

Unix elevation uses sudo to re-execute the current script with root privileges:

# Internal Unix elevation process  
def _check_environment():
    """
    Determine current execution environment and build re-execution command.
    
    Detects whether running under CPython, Nuitka, PyInstaller, or other
    packaging system and constructs appropriate sudo command.
    """

Unix Dependencies:

  • sudo: Must be available in system PATH
  • Standard Unix process APIs

Unix Behavior:

  • Locates sudo executable in PATH
  • Prompts for password if required
  • Re-executes current script/binary with root privileges
  • Passes through all command-line arguments
  • Returns child process exit code

Execution Environment Detection

The elevation system automatically detects various Python execution environments:

CPython Detection

  • Standard Python interpreter execution
  • Re-executes: python script.py args...

Nuitka Detection

  • Detects __compiled__ global variable
  • Re-executes compiled binary directly
  • Handles both standalone and non-standalone modes

Frozen Executable Detection

  • Detects sys.frozen attribute (PyInstaller, cx_freeze, py2exe)
  • Re-executes frozen executable directly
  • Preserves executable path and arguments

Environment Detection Matrix

EnvironmentDetection MethodRe-execution Command
CPythonDefault casepython script.py args
Nuitka__compiled__ in globals./compiled_binary args
PyInstallersys.frozen == True./frozen_exe args
cx_freezesys.frozen == True./frozen_exe args
py2exesys.frozen == True./frozen_exe args

Security Considerations

Input Validation

  • All arguments are properly quoted to prevent injection attacks
  • Absolute paths used to prevent PATH manipulation
  • Command construction uses safe string joining methods

Privilege Validation

  • Always check elevation success with is_admin() after elevation
  • Don't assume elevation succeeded without verification
  • Implement appropriate error handling for elevation failures

Best Practices

def secure_admin_operation():
    """Example of secure privilege elevation pattern."""
    
    # Check if already elevated
    if is_admin():
        perform_privileged_operation()
        return
    
    # Request elevation
    print("This operation requires administrator privileges.")
    try:
        elevate(secure_admin_operation)
    except Exception as e:
        print(f"Elevation failed: {e}")
        return
        
def perform_privileged_operation():
    """Perform operation that requires admin rights."""
    
    # Verify elevation succeeded
    if not is_admin():
        raise PermissionError("Operation requires administrator privileges")
    
    # Proceed with privileged operations
    print("Performing administrative task...")

Error Handling

Common Elevation Scenarios

User Cancels UAC (Windows):

  • UAC dialog cancelled by user
  • Returns exit code 1223 (ERROR_CANCELLED)
  • Handle gracefully in calling code

Sudo Password Cancelled (Unix):

  • User cancels sudo password prompt
  • Returns non-zero exit code
  • May indicate authentication failure

Missing Dependencies:

  • Windows: Missing win32 modules
  • Unix: sudo not installed or in PATH
  • Graceful degradation with informative error messages

Exception Handling Pattern

import sys
from command_runner.elevate import elevate, is_admin

def main():
    try:
        if not is_admin():
            print("Requesting elevation...")
            elevate(main)
        else:
            print("Running with privileges")
            # Perform administrative operations
    except EnvironmentError as e:
        print(f"Platform not supported: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Elevation failed: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()

Install with Tessl CLI

npx tessl i tessl/pypi-command-runner

docs

core-execution.md

index.md

privilege-elevation.md

process-management.md

utilities.md

tile.json