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

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

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

我现在运行的是Win7,计划最终迁移到Win10。我每天都运行这些程序,一一运行它们并为每个程序输入名称/密码非常耗时。我想我应该“自动化那些无聊的事情”并让 Python 来做。

关于这个问题(如何在 Windows 上以提升的权限运行 python 脚本),答案就在那里,并且发布了名为“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())
python python-2.7 python-3.x
3个回答
2
投票

看起来

types.TupleType
types.ListType
在 Python 3 中不存在。请尝试以下操作:

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

说“cmdLine不是序列”后的值错误并不完全准确,因为字符串是序列,但确实应该引发

ValueError
。我可能会将其改写为“cmdLine 应该是非空元组或列表,或者 None”。您可以更新它以更广泛地检查
cmdLine
是否是非字符串可迭代,但这可能有点过头了。


2
投票

以下示例演示了在 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()

0
投票

以下示例演示如何以管理员权限运行脚本。

https://stackoverflow.com/a/78251157/23132460

© www.soinside.com 2019 - 2024. All rights reserved.