如何在Windows上以提升的特权运行python脚本

我正在编写一个需要执行管理任务的pyqt应用程序。我希望以提升的特权启动脚本。我知道这个问题在SO或其他论坛中被问过很多次。但是人们建议的解决方案是看看这个SO问题 从Python脚本中请求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."

它实际上请求提升权限,但打印行从未执行。有人可以帮助我成功运行以上代码。提前致谢。

回答:

我的脚本可以与Preston Landers于2010年编写的模块/脚本一起使用。经过两天的互联网浏览后,我发现了该脚本,因为该脚本已深深地藏在pywin32邮件列表中。使用此脚本,可以更轻松地检查用户是否为admin,如果不是,则询问UAC / admin权限。它确实在单独的窗口中提供输出,以找出代码在做什么。脚本中还包含有关如何使用代码的示例。为了所有人在Windows上寻找UAC的利益,请查看以下代码。我希望它可以帮助寻求相同解决方案的人。在你的主脚本中可以使用以下命令:

import admin

if not admin.isUserAdmin():

admin.runAsAdmin()

实际的代码是:

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

以上是 如何在Windows上以提升的特权运行python脚本 的全部内容, 来源链接: utcz.com/qa/413631.html

回到顶部