Home >Backend Development >Python Tutorial >How to Run a Python Script with Elevated Privileges on Windows?
How to Run a Script with Elevated Privileges on Windows
Many applications require elevated privileges to access specific resources or perform privileged tasks. In Windows, UAC (User Account Control) safeguards the operating system and user data by preventing unauthorized changes. This article addresses how to execute a script with elevated privileges on Windows.
Solution Using 'isUserAdmin' and 'runAsAdmin' Functions
In response to the provided code snippet and subsequent issues, a more robust solution is available through the modules developed by Preston Landers. The module defines two key functions: isUserAdmin and runAsAdmin.
isUserAdmin
This function verifies if the current user possesses administrative privileges.
runAsAdmin
This function elevates the privileges of the script by prompting the user for UAC authorization.
Example Usage
import admin if not admin.isUserAdmin(): admin.runAsAdmin()
This code fragment checks if the user is an admin. If not, it prompts for UAC confirmation and restarts the script with elevated privileges.
Improved Version Using 'pyuac' Package
Since the original script's creation, the author has updated and released it as a Python package called 'pyuac':
Installation:
pip install pyuac pip install pypiwin32
Example Usage using pyuac
import pyuac def main(): print("Do admin stuff here.") if __name__ == "__main__": if not pyuac.isUserAdmin(): print("Re-launching as admin!") pyuac.runAsAdmin() else: main()
The above is the detailed content of How to Run a Python Script with Elevated Privileges on Windows?. For more information, please follow other related articles on the PHP Chinese website!