如何在 Windows 上以提升的权限运行脚本? [英] How to run a script with elevated privilege on windows?

查看:87
本文介绍了如何在 Windows 上以提升的权限运行脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to puzzle out how to run a bunch of applications which all require elevated permissions. Applications like DameWare, MSC.exe, PowerShell.exe, and the SCCM Manager Console, which are all used in my daily work routine.

我现在正在运行 Win7,并计划最终迁移到 Win10.我每天都运行这些程序,并且一个一个地运行它们并为每个程序输入名称/密码是很耗时的.我想我只是自动化无聊的东西",让 Python 来做.

I am running Win7 right now, with plans to move to Win10 eventually. Every day I run these programs and it is time consuming to run them one by one and type in name/password for each. I figured I'd just 'automate the boring stuff' and let Python do it.

关于这个问题(如何运行python在 Windows 上具有提升权限的脚本)答案就在那里,并且发布了名为admin"的旧模块的代码.然而,它是用 Python 2+ 编写的,在 Python 3.5+ 上运行得不太好.我已经用我有限的 Python 知识做了我所知道的事情,但是当它尝试运行时我不断收到错误

Over on this question (How to run python script with elevated privilege on windows) the answer is there and the code for an old module called 'admin' was posted. However it was written in Python 2+ and doesn't work so well with Python 3.5+. I've done what I know to do with my limited python knowledge but I keep getting errors when it attempts to run

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 转换/等效文件.

I've done some research and all I can find is the Python 2 documentation or examples, but not a Python 3 conversion/equivalent.

这是 admin.py 源代码,我已尽我所能将其升级到 Python 3.5+.您能提供的任何帮助将不胜感激!

Here is the admin.py source, I've done what I can to bring it up to Python 3.5+. Any help you can offer will be appreciated!

#!/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())

推荐答案

看起来 types.TupleTypetypes.ListType 在 Python 3 中不存在.试试改为:

It looks like types.TupleType and types.ListType do not exist in Python 3. Try the following instead:

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

说cmdLine 不是序列"后的值错误并不完全准确,因为字符串是序列,但确实应该引发 ValueError.我可能会将它改写为cmdLine 应该是一个非空的元组或列表,或者 None".您可以更新它以更广泛地检查 cmdLine 是否是非字符串可迭代的,但这可能有点矫枉过正.

The value error after saying that "cmdLine is not a sequence" is not exactly accurate because strings are sequences, but should indeed raise a ValueError. I might reword it to "cmdLine should be a non-empty tuple or list, or None." You could update it to more broadly check whether cmdLine is a non-string iterable, but that might be overkill.

这篇关于如何在 Windows 上以提升的权限运行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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