在 Windows 中请求管理员访问 Python 函数

问题描述 投票:0回答:2

我想使用 Python 函数将文件列表复制到 Windows 系统目录

(C:\Windows)

我有一个功能:

import shutil

def copy_list(src_list, dst):
    for file in src_list:
        shutil.copy(file, dst)

我想这样称呼它:

def copy_as_admin():
    #... some code to obtain user elevation ...

    copy_list(files_list, "C:\\Windows\")

我怎样才能做到这一点? PS:我正在使用 Python3,我在这个线程中尝试了解决方案, 如何在 Windows 上以提升的权限运行 python 脚本 但这些解决方案适用于 Python 版本 2.

python windows python-3.x pywin32 win32com
2个回答
2
投票

以下示例基于 Cyrbil 的出色工作。特别地,引入了两个枚举。第一个允许轻松指定如何打开提升的程序,第二个有助于在需要轻松识别错误时提供帮助。请注意,如果您希望将所有命令行参数传递给新进程,

sys.argv[0]
可能应该替换为函数调用:
subprocess.list2cmdline(sys.argv)
.

#! /usr/bin/env python3
import ctypes
import enum
import sys


# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx


class SW(enum.IntEnum):

    HIDE = 0
    MAXIMIZE = 3
    MINIMIZE = 6
    RESTORE = 9
    SHOW = 5
    SHOWDEFAULT = 10
    SHOWMAXIMIZED = 3
    SHOWMINIMIZED = 2
    SHOWMINNOACTIVE = 7
    SHOWNA = 8
    SHOWNOACTIVATE = 4
    SHOWNORMAL = 1


class ERROR(enum.IntEnum):

    ZERO = 0
    FILE_NOT_FOUND = 2
    PATH_NOT_FOUND = 3
    BAD_FORMAT = 11
    ACCESS_DENIED = 5
    ASSOC_INCOMPLETE = 27
    DDE_BUSY = 30
    DDE_FAIL = 29
    DDE_TIMEOUT = 28
    DLL_NOT_FOUND = 32
    NO_ASSOC = 31
    OOM = 8
    SHARE = 26


def bootstrap():
    if ctypes.windll.shell32.IsUserAnAdmin():
        main()
    else:
        hinstance = ctypes.windll.shell32.ShellExecuteW(
            None, 'runas', sys.executable, sys.argv[0], None, SW.SHOWNORMAL
        )
        if hinstance <= 32:
            raise RuntimeError(ERROR(hinstance))


def main():
    # Your Code Here
    print(input('Echo: '))


if __name__ == '__main__':
    bootstrap()

2
投票

您不能在运行时在 Windows 上更改权限。

应用程序需要有清单(不适合 python)或作为特权用户运行。

当应用程序启动且权限太低时,您可以要求用户以管理员身份运行,或者通过调用

runas
让应用程序以提升的权限重新启动。

import ctypes

if not ctypes.windll.shell32.IsUserAnAdmin():
    print('Not enough priviledge, restarting...')
    import sys
    ctypes.windll.shell32.ShellExecuteW(
        None, 'runas', sys.executable, ' '.join(sys.argv), None, None)
else:
    print('Elevated privilege acquired')
© www.soinside.com 2019 - 2024. All rights reserved.