栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

import adminif 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.5import sys, os, traceback, typesdef 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 pre %s" % (procHandle, rc)    else:        rc = None    return rcdef 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 rcif __name__ == "__main__":    sys.exit(test())


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614570.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号