Python Windows权限提升

3

所以,我想以管理员模式(UAC)运行程序。

经过一番搜寻,我找到了以下内容:

import os
import types
from traceback import print_exc
from sys import argv, executable




def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            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 = executable

    if cmdLine is None:
        cmdLine = [python_exe] + 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: ", argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc
if __name__ == "__main__":
    if not isUserAdmin():
        runAsAdmin()

这会要求用户授予管理员权限,但我有两个主要问题:

1.用户需要给程序权限。(对渗透测试来说是有问题的)

2.每次运行程序时,用户都需要授予程序权限。(这很可疑)

有办法绕过这个限制吗?

附注:Windows 7且无直接访问权限。


Windows 7 的文件属性或控制面板中是否有任何功能可以自动允许某些程序默认以提升的权限运行? - NuclearPeon
1
只有系统服务才能绕过UAC提升管理员权限。例如,当请求最高权限时,任务计划程序服务会执行此操作。因此,您可以创建一个按需运行的任务。 - Eryk Sun
1个回答

2

有没有办法从Python脚本中创建一个任务计划程序? - Richard Paul Astley
1
你可以使用schtasks在Windows cmd shell中创建定时任务。理论上,你应该能够使用Python的子进程来运行schtasks命令。这里有一个链接,讨论了如何做到这一点...https://dev59.com/FnE85IYBdhLWcg3wikIu - abaldwin99
1
@RichardPaulAstley,在创建任务时使用选项/rl highest使其以提升权限运行。然后通过schtasks.exe /run /tn [taskname]按需运行任务。 - Eryk Sun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接