从 Python 脚本中请求 UAC 提升? [英] Request UAC elevation from within a Python script?

查看:48
本文介绍了从 Python 脚本中请求 UAC 提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 Python 脚本在 Vista 上复制文件.当我从普通的 cmd.exe 窗口运行它时,没有生成错误,但文件没有被复制.如果我以管理员身份"运行 cmd.exe 然后运行我的脚本,它就可以正常工作.

I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run cmd.exe "as administator" and then run my script, it works fine.

这是有道理的,因为用户帐户控制 (UAC) 通常会阻止许多文件系统操作.

This makes sense since User Account Control (UAC) normally prevents many file system actions.

有没有一种方法可以从 Python 脚本中调用 UAC 提升请求(那些对话框中会说某某应用程序需要管理员访问权限,可以吗?")

Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")

如果这是不可能的,我的脚本有没有办法至少检测到它没有被提升,所以它可以正常失败?

If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?

推荐答案

截至 2017 年,实现此目的的简单方法如下:

As of 2017, an easy method to achieve this is the following:

import ctypes, sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    # Code of your program here
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

如果您使用的是 Python 2.x,那么您应该将最后一行替换为:

If you are using Python 2.x, then you should replace the last line for:

ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)

另请注意,如果您将 Python 脚本转换为可执行文件(使用诸如 py2execx_freezepyinstaller 之类的工具),那么您应该在第四个参数中使用 sys.argv[1:] 而不是 sys.argv.

Also note that if you converted you python script into an executable file (using tools like py2exe, cx_freeze, pyinstaller) then you should use sys.argv[1:] instead of sys.argv in the fourth parameter.

这里的一些优点是:

  • 不需要外部库.它只使用标准库中的 ctypessys.
  • 适用于 Python 2 和 Python 3.
  • 无需修改文件资源,也无需创建清单文件.
  • 如果您不在 if/else 语句下方添加代码,代码将永远不会执行两次.
  • 您可以在最后一行获取 API 调用的返回值,并在失败时采取行动(代码 <= 32).检查可能的返回值 这里.
  • 您可以通过修改第六个参数来更改衍生进程的显示方式.

底层 ShellExecute 调用的文档是 此处.

Documentation for the underlying ShellExecute call is here.

这篇关于从 Python 脚本中请求 UAC 提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆