如何在Windows上运行具有提升权限的脚本?

时间:2017-01-27 14:47:13

标签: python python-2.7 python-3.x

我一直在试图弄清楚如何运行一堆所有需要提升权限的应用程序。像DameWare,MSC.exe,PowerShell.exe和SCCM Manager Console这样的应用程序,它们都在我的日常工作中使用。

我现在正在运行Win7,计划最终转移到Win10。每天我都运行这些程序,逐个运行它们并为每个程序键入名称/密码是很费时的。我想我只是'自动化无聊的东西'并让Python做到。

关于这个问题(How to run python script with elevated privilege on windows),答案就在那里,并且发布了一个名为“admin”的旧模块的代码。然而,它是用Python 2+编写的,并且在Python 3.5+中运行得不好。我已经做了我所知道的有限的python知识,但是当它试图运行时我一直都会遇到错误

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    runAsAdmin('cmd.exe')
  File "I:\Scripting\Python\admin.py", line 41, in runAsAdmin
    elif type(cmdLine) not in (types.TupleType,types.ListType):
AttributeError: module 'types' has no attribute 'TupleType'

我做了一些研究,我所能找到的只是Python 2文档或示例,但不是Python 3转换/等效。

这是admin.py源代码,我已经尽力将其用于Python 3.5+。如果您有任何帮助,我们将不胜感激!

#!/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 = input('Press Enter to exit.')
    return rc


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

2 个答案:

答案 0 :(得分:2)

在Python 3中看起来似乎types.TupleTypetypes.ListType。请尝试以下方法:

elif type(cmdLine) not in (tuple, list)

表示&#34; cmdLine不是序列后的值错误&#34;不完全准确,因为字符串是序列,但确实应该提出ValueError。我可能会将其改为&#34; cmdLine应该是非空元组或列表,或者是无。&#34;您可以更新它以更广泛地检查cmdLine是否是非字符串可迭代的,但这可能是过度的。

答案 1 :(得分:1)

以下示例演示了在Windows上使用提升的权限运行程序的简单方法。枚举旨在简化与操作系统交互时所需的一些值。第一个允许轻松指定如何打开提升的程序,第二个允许在需要轻松识别错误时提供帮助。请注意,如果您希望将所有命令行参数传递给新进程,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()