Home >Backend Development >Python Tutorial >How to Run a Python Script with Elevated Privileges on Windows?

How to Run a Python Script with Elevated Privileges on Windows?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 17:52:10579browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn