如何在Windows上使用提升的权限运行python脚本

sun*_*ima 51 python windows admin elevated-privileges

我正在编写一个需要执行管理任务的pyqt应用程序.我更喜欢用提升权限启动我的脚本.我知道在SO或其他论坛中多次询问此问题.但人们建议的解决方案是从Python脚本中查看这个SO问题 请求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."
Run Code Online (Sandbox Code Playgroud)

它实际上要求提升权限,但打印行永远不会被执行.有人可以帮我成功运行上面的代码.提前致谢.

sun*_*ima 68

谢谢大家的回复.我的脚本使用了Preston Landers在2010年编写的模块/脚本.经过两天浏览互联网后,我可以找到脚本,因为它被深深隐藏在pywin32邮件列表中.使用此脚本可以更轻松地检查用户是否为admin,如果没有,则请求UAC/admin权限.它确实在单独的窗口中提供输出以找出代码正在做什么.有关如何使用脚本中包含的代码的示例.为了所有在Windows上寻找UAC的人的利益,请查看此代码.我希望它可以帮助寻找相同解决方案的人.它可以在你的主脚本中使用这样的东西: -

import admin
if not admin.isUserAdmin():
        admin.runAsAdmin()
Run Code Online (Sandbox Code Playgroud)

实际代码是: -

#!/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())
Run Code Online (Sandbox Code Playgroud)

  • 这是在github3上为python3分叉的相同脚本https://gist.github.com/sylvainpelissier/ff072a6759082590a4fe8f7e070a4952 (2认同)

and*_*oke 10

回答你从某人那里得到的代码时,ShellExecuteEx不会将其STDOUT发布回原始shell.所以你不会看到"我现在是根",即使代码可能工作正常.

而不是打印东西,尝试写入文件:

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)
with open("somefilename.txt", "w") as out:
    print >> out, "i am root"
Run Code Online (Sandbox Code Playgroud)

然后查看文件.

  • 说谢谢你是一种奇怪的方式,但欢迎你. (7认同)
  • @deenbandhu,如​​果您可以跳过提示,那么有史以来编写的每个病毒都会这样做,并且您会不断被感染。这是一个永远不会消失的功能。 (2认同)

del*_*rst 8

我找到了一个非常简单的解决这个问题的方法。

  1. 创建快捷方式 python.exe
  2. 将快捷方式目标更改为类似 C:\xxx\...\python.exe your_script.py
  3. 在快捷方式的属性面板中点击“高级...”,然后点击“以管理员身份运行”选项

我不确定这些选项的拼写是否正确,因为我使用的是中文版Windows。

  • 该方法也可以解释为:以管理员身份运行 python,然后执行脚本。然后所有脚本将自动具有管理员访问权限。 (4认同)

Flo*_* B. 6

这是一个带有stdout重定向的解决方案:

def elevate():
    import ctypes, win32com.shell.shell, win32event, win32process
    outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
    if ctypes.windll.shell32.IsUserAnAdmin():
        if os.path.isfile(outpath):
            sys.stderr = sys.stdout = open(outpath, 'w', 0)
        return
    with open(outpath, 'w+', 0) as outfile:
        hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
            lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
        while True:
            hr = win32event.WaitForSingleObject(hProc, 40)
            while True:
                line = outfile.readline()
                if not line: break
                sys.stdout.write(line)
            if hr != 0x102: break
    os.remove(outpath)
    sys.stderr = ''
    sys.exit(win32process.GetExitCodeProcess(hProc))

if __name__ == '__main__':
    elevate()
    main()
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一个只需要ctypes模块的解决方案.支持pyinstaller包装程序.

#!python
# coding: utf-8
import sys
import ctypes

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True

    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print 'Command line: ', executable, argument_line
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None


if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print 'I have admin privilege.'
        raw_input('Press ENTER to exit.')
    elif ret is None:
        print 'I am elevating to admin privilege.'
        raw_input('Press ENTER to exit.')
    else:
        print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
Run Code Online (Sandbox Code Playgroud)


Ben*_*nny 5

值得一提的是,如果您打算使用PyInstaller打包应用程序并希望避免自己支持该功能,则可以传递--uac-admin--uac-uiaccess参数以在启动时请求 UAC 提升。


小智 5

  1. 制作一个批处理文件
  2. 添加 python.exe "(your py file here)" 带引号
  3. 保存批处理文件
  4. 右键单击,然后单击以管理员身份运行