Platform agnostic command and shell execution tool with timeout handling, live output capture, and UAC/sudo privilege elevation
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
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
"""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
"""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)
"""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 monitoringwin32process: Process managementwin32com.shell.shell: UAC elevation APIsWindows Behavior:
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 PATHUnix Behavior:
The elevation system automatically detects various Python execution environments:
python script.py args...__compiled__ global variablesys.frozen attribute (PyInstaller, cx_freeze, py2exe)| Environment | Detection Method | Re-execution Command |
|---|---|---|
| CPython | Default case | python script.py args |
| Nuitka | __compiled__ in globals | ./compiled_binary args |
| PyInstaller | sys.frozen == True | ./frozen_exe args |
| cx_freeze | sys.frozen == True | ./frozen_exe args |
| py2exe | sys.frozen == True | ./frozen_exe args |
is_admin() after elevationdef 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...")User Cancels UAC (Windows):
Sudo Password Cancelled (Unix):
Missing Dependencies:
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