util_admin_check

Path: /utilities/util_admin_check.py

Overview

Provides functions to detect and ensure administrative privileges on Windows, including relaunching the current script with elevated rights if necessary.

Purpose & Use Cases

Check whether the current process has administrator privileges before performing privileged operations.

Automatically relaunch the script with a User Account Control (UAC) prompt to obtain elevated rights.

Dependencies

ctypes (standard library) for Windows API calls.

utilities.util_logger for logging and utilities.util_error_popup for user-facing error dialogs.

Configuration & Parameters

Parameter Type Description Default
None N/A No configurable parameters N/A

Usage Example

python util_admin_check.py

Behavior & Implementation

is_admin() calls ctypes.windll.shell32.IsUserAnAdmin() to determine if the process has elevated rights. run_as_admin() constructs the current executable or script path and arguments, then invokes ShellExecuteW with the runas verb to trigger a UAC prompt. ensure_admin() checks admin status and, if not elevated, logs a warning, calls run_as_admin(), and exits to allow the new elevated process to take over.

Error Handling

Errors in is_admin() are caught and logged, returning False on failure. Failures to relaunch with elevation in run_as_admin() log exceptions, show an error popup, and exit the process with a non-zero code. ensure_admin() exits after requesting elevation to prevent further execution under insufficient privileges.

Security Considerations

This module uses Windows UAC to elevate privileges, ensuring that elevation requests follow OS security prompts. Command-line arguments and script paths are quoted to mitigate injection risks. Only applicable on Windows platforms.

Logging

Uses utilities.util_logger.logger with levels: DEBUG for successful admin detection, INFO for elevation attempts, WARNING when elevation is required, and ERROR when checks or elevation fail. Example: logger.warning("Administrator privileges required; relaunching with UAC prompt...").

Testing & Validation

Unit tests can mock ctypes.windll.shell32.IsUserAnAdmin to simulate admin/non-admin cases. Manual validation on Windows: run the module under standard and elevated contexts to confirm UAC prompts and proper behavior.

Author

Author: Raven Development Team