当前位置: 首页 > 面试题库 >

如何在Windows上以提升的特权运行python脚本

谷光誉
2023-03-14
问题内容

我正在编写一个需要执行管理任务的pyqt应用程序。我希望以提升的特权启动脚本。我知道这个问题在SO或其他论坛中被问过很多次。但是人们建议的解决方案是看看这个SO问题 从Python脚本中请求UAC提升吗?

但是,我无法执行链接中给出的示例代码。我已将此代码放在主文件之上,并尝试执行它。

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)
print "I am root now."

它实际上请求提升权限,但打印行从未执行。有人可以帮助我成功运行以上代码。提前致谢。


问题答案:

我的脚本可以与Preston Landers于2010年编写的模块/脚本一起使用。经过两天的互联网浏览后,我发现了该脚本,因为该脚本已深深地藏在pywin32邮件列表中。使用此脚本,可以更轻松地检查用户是否为admin,如果不是,则询问UAC / admin权限。它确实在单独的窗口中提供输出,以找出代码在做什么。脚本中还包含有关如何使用代码的示例。为了所有人在Windows上寻找UAC的利益,请查看以下代码。我希望它可以帮助寻求相同解决方案的人。在你的主脚本中可以使用以下命令:

import admin
if not admin.isUserAdmin():
        admin.runAsAdmin()

实际的代码是:

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5


import sys, os, traceback, types

def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print "Admin check failed, assuming not an admin."
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)

def runAsAdmin(cmdLine=None, wait=True):

    if os.name != 'nt':
        raise RuntimeError, "This function is only implemented on Windows."

    import win32api, win32con, win32event, win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType,types.ListType):
        raise ValueError, "cmdLine is not a sequence."
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    cmdDir = ''
    showCmd = win32con.SW_SHOWNORMAL
    #showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None

    return rc

def test():
    rc = 0
    if not isUserAdmin():
        print "You're not an admin.", os.getpid(), "params: ", sys.argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", sys.argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc


if __name__ == "__main__":
    sys.exit(test())


 类似资料:
  • 问题内容: 我想编写一个简单的python脚本来完成特定的工作。我花了一些时间从网站链接信息。 在正确的时间单击这些链接的最佳方法是什么?我是否需要计算当前电流与列表中的电流之间的时间间隔并睡眠一会儿? 我真的停留在这一点上,并欢迎任何可能有用的想法。 问题答案: 看一下Python的sched模块。

  • 问题内容: 我在计算机上安装了两个版本的Python(版本2.6和2.5)。我想为一个项目运行2.6,为另一个项目运行2.5。 如何指定要使用的商品? 我正在使用Windows XP SP2。 问题答案: 运行不同的Python副本就像启动正确的可执行文件一样容易。您提到您只是通过键入从命令行启动python实例。 这在Windows下的作用是拖移环境变量,检查可执行文件,批处理文件(),命令文件

  • 问题内容: 我有一个简单的脚本blah.py(使用Python 2): 如果我通过以下方式执行脚本: 它输出参数,但是如果我通过以下方式执行脚本: 发生错误: 因此参数不会传递给脚本。 PATH中的python.exe。路径中也包含blah.py的文件夹。 python.exe是执行* .py文件的默认程序。 问题是什么? 问题答案: 执行脚本而不在前面键入“ python”时,你需要了解有关Wi

  • 我目前正在使用Protobuf插件生成一些定制的C#代码,给出一组Protobuf文件。它在Linux上运行良好,我也希望在Windows上运行它,以便直接从我的Visual Studio项目生成此代码。 以下是我当前(未成功)使用的命令行: 这是我得到的错误: --my-plugin\u out:protoc gen my plugin:%1 n'est pas unie application

  • 问题内容: 我是python的新手,已经学习了几周。但是,现在我刚刚更改了操作系统,现在正在使用ubuntu,并且无法在终端上运行任何脚本。 我确定有, 但是当我去终端输入时,例如 终端显示了这样的错误消息 python:无法打开文件“ test.py”:[Errno 2]没有这样的文件或目录 我该怎么办? 我必须将文件保存在任何特定的文件夹中以使其在终端上运行吗? 问题答案: 这个错误: pyt

  • 问题内容: 这个问题已经在这里有了答案 : 8年前关闭。 可能的重复: 在Windows上设置Python,不要在cmd中键入python 当我在Linux甚至从命令行的Mac OS上使用python时,我会利用shebang并直接运行一些脚本,例如:。我确实需要赋予此脚本可执行权限,仅此而已。 现在,我刚刚在Windows 7上安装了Python 3.1.2,并且希望能够从命令行执行相同的操作。