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

编程入门 行业动态 更新时间:2024-10-27 21:22:51
本文介绍了如何在 Windows 上以提升的权限运行脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个需要执行管理任务的 pyqt 应用程序.我更愿意以提升权限启动我的脚本.我知道这个问题在 SO 或其他论坛中被问过很多次.但是人们建议的解决方案是看看这个 SO question从 Python 脚本中请求 UAC 提升?

I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many times in SO or in other forum. But the solution people are suggesting is to have a look at this SO question Request UAC elevation from within a Python script?

但是,我无法执行链接中给出的示例代码.我已将此代码放在主文件的顶部并尝试执行它.

However, I am unable to execute the sample code given in the link. I have put this code on top of the main file and tried to execute it.

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."

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

It actually ask permission to elevate but print line never get executed. Somebody can help me to run the above code successfully. Thanks in advance.

推荐答案

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

Thank you all for your reply. I have got my script working with the module/ script written by Preston Landers way back in 2010. After two days of browsing the internet I could find the script as it was was deeply hidden in pywin32 mailing list. With this script it is easier to check if the user is admin and if not then ask for UAC/ admin right. It does provide output in separate windows to find out what the code is doing. Example on how to use the code also included in the script. For the benefit of all who all are looking for UAC on windows have a look at this code. I hope it helps someone looking for same solution. It can be used something like this from your main script:-

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 上以提升的权限运行脚本?

本文发布于:2023-11-24 08:23:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上以   脚本   权限   如何在   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!