在 Windows 平台上以管理员权限运行 Python 应用

121 阅读2分钟

在 Windows 平台上,我有一个 Python 程序,它在被调用后会记住其状态,并在系统崩溃或重新启动时恢复状态。该程序实际上运行一些其他可执行程序,或者从技术术语上讲是框架类型的。典型的场景是可执行程序需要以管理员模式运行,第一次通过后,但在从崩溃或重新启动中恢复后失败。我认为我需要以管理员模式调用恢复的应用程序。如何才能实现这一点,提前谢谢!

2、解决方案

为了使 Python 应用在 Windows 平台上以管理员权限运行,可以采用以下解决方案:

  1. 使用 ctypes 模块:
import ctypes

def is_admin():
    """Check if the current user has administrator privileges."""
    try:
        # Get the current user's token.
        token = ctypes.windll.kernel32.GetCurrentProcessToken()
        # Check if the user is a member of the Administrators group.
        is_admin = ctypes.windll.advapi32.CheckTokenMembership(token, ctypes.c_wchar_p(b'Administrators'), 
ctypes.pointer(ctypes.c_bool()))
        return is_admin
    except:
        return False

def run_as_admin(cmd):
    """Run the specified command as an administrator."""
    if is_admin():
        # If the current user is an administrator, run the command directly.
        return subprocess.Popen(cmd)
    else:
        # If the current user is not an administrator, elevate the privileges.
        create_process_flags = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP
        startup_info = subprocess.STARTUPINFO()
        startup_info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        startup_info.wShowWindow = subprocess.SW_HIDE
        return subprocess.Popen(cmd, startupinfo=startup_info, creationflags=create_process_flags)

if __name__ == "__main__":
    # Check if the current user has administrator privileges.
    if is_admin():
        print("The current user has administrator privileges.")
    else:
        print("The current user does not have administrator privileges.")

    # Run the specified command as an administrator.
    cmd = "python your_python_script.py"
    process = run_as_admin(cmd)
  1. 使用 subprocess 模块:
import subprocess

def run_as_admin(cmd):
    """Run the specified command as an administrator."""
    try:
        # Create a new process with administrator privileges.
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 
creationflags=subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP)
        # Wait for the process to complete.
        output, error = process.communicate()
        # Check the exit code of the process.
        if process.returncode == 0:
            # The command ran successfully.
            return output
        else:
            # The command failed.
            raise Exception(error)
    except:
        raise Exception("Failed to run the command as an administrator.")

if __name__ == "__main__":
    # Run the specified command as an administrator.
    cmd = "python your_python_script.py"
    output = run_as_admin(cmd)
    print(output)
  1. 使用 win32api 模块:
import win32api

def run_as_admin(cmd):
    """Run the specified command as an administrator."""
    try:
        # Get the current user's token.
        token = win32api.OpenProcessToken(win32api.GetCurrentProcess(), win32api.TOKEN_ALL_ACCESS)
        # Create a new token with administrator privileges.
        new_token = win32api.DuplicateTokenEx(token, win32api.TOKEN_ALL_ACCESS, None, 
win32api.TOKEN_ELEVATION, win32api.TOKEN_ELEVATION, None)
        # Create a new process with the new token.
        process = win32api.CreateProcessAsUser(new_token, None, cmd, None, None, False, 
win32api.CREATE_NEW_CONSOLE | win32api.CREATE_NEW_PROCESS_GROUP, None, None, 
win32api.STARTUPINFO())
        # Wait for the process to complete.
        win32api.WaitForSingleObject(process, -1)
        # Check the exit code of the process.
        if win32api.GetExitCodeProcess(process) == 0:
            # The command ran successfully.
            return True
        else:
            # The command failed.
            raise Exception("Failed to run the command as an administrator.")
    except:
        raise Exception("Failed to run the command as an administrator.")

if __name__ == "__main__":
    # Run the specified command as an administrator.
    cmd = "python your_python_script.py"
    run_as_admin(cmd)

以上是几种在 Windows 平台上以管理员权限运行 Python 应用的解决方案,您可以根据自己的需要选择合适的方法。