def runAsAdmin(cmdLine=None, wait=True): """Attempt to relaunch the current script as an admin using the same command line parameters. Pass cmdLine in to override and set a new command. It must be a list of [command, arg1, arg2...] format. Set wait to False to avoid waiting for the sub-process to finish. You will not be able to fetch the exit code of the process if wait is False. Returns the sub-process return code, unless wait is False in which case it returns None. @WARNING: this function only works on Windows. """ if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.") import win32api, win32con, win32event, win32process, pywintypes 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 not isinstance(cmdLine, (tuple, list)): 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 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) try: procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) except pywintypes.error: raise OSError if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) else: rc = None return rc
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], ) params = " ".join(['"%s"' % (x, ) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' procInfo = ShellExecuteEx(nShow=1, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params)
def elevate_privilege(cmd_line_seq: list = None, wait: bool = True): python_exe = sys.executable if cmd_line_seq is None: cmd_line_seq = [python_exe] + sys.argv elif not isinstance(cmd_line_seq, ( list, tuple, )): raise ValueError script_to_run = f'"{cmd_line_seq[0]}"' params = " ".join(f'"{x}"' for x in cmd_line_seq[1:]) # input(f'file = {script_to_run}\nparams = {params}\nEnter to continue...') procInfo = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=script_to_run, lpParameters=params) if wait: procHandle = procInfo['hProcess'] _ = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) return_code = win32process.GetExitCodeProcess(procHandle) print("Process handle {} returned code {}".format( procHandle, return_code)) else: return_code = None return return_code
def run_as_admin(commands, cmdLine=None, wait=True): ''' based on --> https://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilege-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] + commands cmd = cmdLine[0] params = ' '.join(commands) showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' 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 run_as_admin(cmd, params): if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.") import win32con, win32event, win32process # noqa: E401 from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon showCmd = win32con.SW_SHOWNORMAL # win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # 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. procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) procHandle = procInfo['hProcess'] win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) if rc != 0: raise subprocess.CalledProcessError(rc, '{cmd} {params}') return rc
def run_elevated(command, args, wait=True): """Run the given command as an elevated user and wait for it to return""" ret = 1 try: if command.find(' ') > -1: command = '"' + command + '"' if platform.system() == 'Windows': import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon logging.debug(command + ' ' + args) process_info = ShellExecuteEx( nShow=win32con.SW_HIDE, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=command, lpParameters=args) if wait: win32event.WaitForSingleObject(process_info['hProcess'], 600000) ret = win32process.GetExitCodeProcess(process_info['hProcess']) win32api.CloseHandle(process_info['hProcess']) else: ret = process_info else: logging.debug('sudo ' + command + ' ' + args) ret = subprocess.call('sudo ' + command + ' ' + args, shell=True) except Exception: logging.exception('Error running elevated command: %s', command) return ret
def runAsAdmin(cmd, wait=True, show=False): if not isUserAdmin(): return 1 # Cannot run as admin if isinstance(cmd, str): splits = cmd.split() exeFile = splits[0] params = ' '.join(splits[1:]) else: exeFile = cmd[0] params = cmdToStr(cmd[1:]) if show: showWindow = win32con.SW_SHOW else: showWindow = win32con.SW_HIDE procInfo = ShellExecuteEx(nShow=showWindow, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=exeFile, lpParameters=params) rc = 0 if wait: procHandle = procInfo['hProcess'] win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) return rc
def run_elevated(args, wait=True): if platform.system() == "Windows": import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon import shlex if type(args) == str: args = shlex.split(args) quoted_args = subprocess.list2cmdline(args[1:]) process_info = ShellExecuteEx( nShow=win32con.SW_SHOW, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=args[0], lpParameters=quoted_args, ) if wait: win32event.WaitForSingleObject(process_info["hProcess"], 600000) ret = win32process.GetExitCodeProcess(process_info["hProcess"]) win32api.CloseHandle(process_info["hProcess"]) else: ret = process_info else: ret = subprocess.call(["sudo"] + args, shell=True) return ret
def _windows_runner(runner, arguments): # type: (str, str) -> int # Old method using ctypes which does not wait for executable to exit nor does get exit code # See https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-shellexecutew # int 0 means SH_HIDE window, 1 is SW_SHOWNORMAL # needs the following imports # import ctypes # ctypes.windll.shell32.ShellExecuteW(None, 'runas', runner, arguments, None, 0) # Method with exit code that waits for executable to exit, needs the following imports # import win32event # monitor process # import win32process # monitor process # from win32com.shell.shell import ShellExecuteEx # from win32com.shell import shellcon # pylint: disable=C0103 (invalid-name) childProcess = ShellExecuteEx( nShow=0, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=runner, lpParameters=arguments, ) # pylint: disable=C0103 (invalid-name) procHandle = childProcess["hProcess"] # pylint: disable=I1101 (c-extension-no-member) win32event.WaitForSingleObject(procHandle, win32event.INFINITE) # pylint: disable=I1101 (c-extension-no-member) exit_code = win32process.GetExitCodeProcess(procHandle) return exit_code
def run_as_admin(cmd: list = None, wait=True): if os.name != "nt": raise NotImplementedError( "This function is only implemented on Windows.") import win32api, win32con, win32event, win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon import types if cmd is None: cmd = [sys.executable] + sys.argv process = '"%s"' % (cmd[0], ) params = " ".join(['"%s"' % (x, ) for x in cmd[1:]]) cmdDir = "" showCmd = win32con.SW_SHOWNORMAL procInfo = ShellExecuteEx( nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=process, lpParameters=params, ) if wait: procHandle = procInfo["hProcess"] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) print(f"Return code: {rc}") else: rc = None return rc
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 = '{}'.format(cmdLine[0]) params = ' '.join(['{}'.format(x, ) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' # causes a UAC elevation prompt 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) else: rc = None
def execute_elevated(*args): # FIXME: support **kwargs from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon import win32process, win32event import winxpgui import win32api import win32con try: hwnd = winxpgui.GetConsoleWindow() except winxpgui.error: hwnd = 0 parameters = "" if not hasattr(sys, "frozen"): # Not running under py2exe exe parameters += "\"" + sys.argv[0] + "\" " parameters += " ".join(map(lambda x: "\"" + str(x) + "\"", args)) print "Executing elevated with parameters " + parameters # TODO: capture output (maybe via named pipe) rc = ShellExecuteEx(hwnd=hwnd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=sys.executable, lpParameters=parameters, nShow=win32con.SW_SHOW) hproc = rc['hProcess'] win32event.WaitForSingleObject(hproc, win32event.INFINITE) exit_code = win32process.GetExitCodeProcess(hproc) if exit_code: raise Exception("Error: subprocess failed (exit code %s)." % exit_code)
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], ) params = " ".join(['"%s"' % (x, ) for x in cmdline[1:]]) showcmd = win32con.SW_SHOWNORMAL lpverb = 'runas' procinfo = ShellExecuteEx(nShow=showcmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpverb, lpFile=cmd, lpParameters=params) if wait: prochandle = procinfo['hProcess'] rc = win32process.GetExitCodeProcess(prochandle) else: rc = None return rc
def run_win(argv, needs_sudo=False, wait=True, cwd=None): """ Run a process on windows. Returns: the exit code of the process if `wait` is `True`, or the PID of the running process if `wait` is `False`. """ 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 # XXX TODO: isn't there a function or something we can call to massage command line params? cmd = winshell_quote(argv[0]) params = " ".join([winshell_quote(x) for x in argv[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE if needs_sudo: lpVerb = 'runas' # causes UAC elevation prompt. else: lpVerb = 'open' # just open the application logger.debug("running %s %s", 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) optional_args = {} if (cwd is not None): optional_args['lpDirectory'] = cwd procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params, **optional_args ) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) logger.debug("Process handle %s returned code %s", (procHandle, rc)) else: # get PID rc = win32process.GetProcessId(procInfo['hProcess']); return rc
def UseCommandLine(*classes, **flags): unregisterInfo = '--unregister_info' in sys.argv unregister = '--unregister' in sys.argv flags['quiet'] = flags.get('quiet', 0) or '--quiet' in sys.argv flags['debug'] = flags.get('debug', 0) or '--debug' in sys.argv flags['unattended'] = flags.get('unattended', 0) or '--unattended' in sys.argv if unregisterInfo: return UnregisterInfoClasses(*classes, **flags) try: if unregister: UnregisterClasses(*classes, **flags) else: RegisterClasses(*classes, **flags) except win32api.error, exc: # If we are on xp+ and have "access denied", retry using # ShellExecuteEx with 'runas' verb to force elevation (vista) and/or # admin login dialog (vista/xp) if flags['unattended'] or exc[0] != winerror.ERROR_ACCESS_DENIED \ or sys.getwindowsversion()[0] < 5: raise from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon import win32process, win32event import winxpgui # we've already checked we are running XP above if not flags['quiet']: print "Requesting elevation and retrying..." new_params = " ".join(['"' + a + '"' for a in sys.argv]) # specifying the parent means the dialog is centered over our window, # which is a good usability clue. # hwnd is unlikely on the command-line, but flags may come from elsewhere hwnd = flags.get('hwnd', None) if hwnd is None: try: hwnd = winxpgui.GetConsoleWindow() except winxpgui.error: hwnd = 0 rc = ShellExecuteEx(hwnd=hwnd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=win32api.GetShortPathName(sys.executable), lpParameters=new_params, lpDirectory=os.getcwd(), nShow=win32con.SW_SHOW) # Output is lost to the new console which opens, so the # best we can do is get the exit code of the process. hproc = rc['hProcess'] win32event.WaitForSingleObject(hproc, win32event.INFINITE) exit_code = win32process.GetExitCodeProcess(hproc) if exit_code: # Even if quiet you get to see this error. print "Error: registration failed (exit code %s)." % exit_code print "Please re-execute this command from an elevated command-prompt" print "to see details about the error." else: if not flags['quiet']: print "Elevated process succeeded."
def run_as_admin(): procInfo = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=sys.executable) procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) return win32process.GetExitCodeProcess(procHandle)
def winSudo(cmd, parameters): if type(parameters) is list: parameters = tools.list2String(parameters) proc_info = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=cmd, lpParameters=parameters) return proc_info
def runAsAdmin(self, 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." cmdLine = cmdLine[0].split() 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) try: 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 except: self.log_action( self.logfile, "There was an error attempting to update your local network settings. Please do so manually." ) self.network_button.set_inconsistent(True) self.network_button.set_label('Enable') return None
def runAsAdmin(cmdLine=None, wait=True): if cmdLine is None: python_exe = sys.executable cmdLine = [python_exe] + sys.argv # run the present Python command with elevation. else: if not isinstance(cmdLine, (tuple, list)): raise ValueError("cmdLine is not a sequence.") cmd = '"{}"'.format(cmdLine[0]) params = " ".join(['"{}"'.format(x) for x in cmdLine[1:]]) if os.name == 'posix': import subprocess cmd = 'sudo {} {}'.format(cmd, params) print('Running command-->', cmd) rc = subprocess.call(cmd, shell=True) elif os.name == 'nt': try: import win32con, win32event, win32process except ImportError: raise ImportError('PyWin32 module has not been installed.') # noinspection PyUnresolvedReferences from win32com.shell.shell import ShellExecuteEx # noinspection PyUnresolvedReferences from win32com.shell import shellcon showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' # causes UAC elevation prompt. print() print("This window is waiting while a child window is run as an Administrator...") print("Running command-->{} {}...".format(cmd, params)) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] if procHandle is None: print("Windows Process Handle is Null. RunAsAdmin did not create a child process.") rc = None else: win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) # print("Process handle %s returned code %s" % (procHandle, rc)) procHandle.Close() else: rc = None else: raise RuntimeError("Unsupported operating system for this module: {}".format(os.name)) return rc
def runAsAdmin(cmdLine=None, wait=True): # If the OS is not a Windows NT OS raise an error that this function will not run if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows" import win32api, win32con, win32event, win32process # Importing specific functions allow functions to be called without full package names from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon # Store the path to the python interpreter in use python_exe = sys.executable if cmdLine is None: # sys.argv is the executable currently running, here we are making a tuple/list with interpreter and script being run cmdLine = [python_exe] + sys.argv # if cmdLine isn't a list or tuple it will not contain the info we need so we will raise an error elif type(cmdLine) not in (types.TupleType, types.ListType): raise ValueError, "cmdLine is not a sequence." # Pull out the first value in cmdLine and save it as a string giving the python interpreter path for later use cmd = '"%s"' % (cmdLine[0], ) # XXX TODO: isn't there a function or something we can call to massage command line params # params stores the running script name as a string for later use, if multiple params passed in will be joined together params = " ".join(['"%s"' % (x, ) for x in cmdLine[1:]]) cmdDir = '' # This determines if we want to show command line or not, since not GUI we don't want to hide the window showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt # 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, # This prevents the parent process from exiting fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) # Waiting on the admin prompt to pop up before moving on if wait is set to true 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 runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.") import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: if sys.argv[0].endswith('.py'): cmdLine = [python_exe] + sys.argv elif sys.argv[0].endswith('.exe'): cmdLine = 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 runAsAdmin(cmdLine=None): # Run the given cmdLine as Admin (Windows) or root (Linux/MacOS) if os.name == "nt": # For Windows procInfo = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb="runas", lpFile=cmdLine.split(" ")[0], lpParameters=" ".join(cmdLine.split(" ")[1:])) else: # For Linux and MacOS os.system("sudo " + cmdLine)
def ahto_print(path): # basic print auto rc = ShellExecuteEx( lpVerb='print', lpFile=path, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS | shellcon.SEE_MASK_DOENVSUBST # NOCLOSEPROCESS: 프로세스 핸들을 반환하도록 합니다. # DOENVSUBST: lpFile에 포함된 환경 변수를 실제 값으로 바꿔주도록 합니다. ) hproc = rc['hProcess'] win32event.WaitForSingleObject(hproc, win32event.INFINITE) exit_code = win32process.GetExitCodeProcess(hproc)
def RunAsAdmin(conn=None, cmdLine=None, showCmd=False, wait=True): if os.name != 'nt': raise (RuntimeError, "This function is only implemented on Windows.") if cmdLine is None: python_exe = sys.executable cmdLine = [python_exe] + sys.argv else: try: #check if list/tuple ",".join(cmdLine) print(cmdLine[0]) except: raise Exception(TypeError, cmdLine, "cmdLine is not a list or a tuple type") cmd = cmdLine[0] params = " ".join([x for x in cmdLine[1:]]) #show shell or keep it hidden if showCmd is True: showCmd = win32con.SW_SHOWNORMAL elif showCmd is False: showCmd = win32con.SW_HIDE else: raise Exception(ArgError, "showCmd: Invalid value - ", showCmd) lpVerb = 'runas' # causes UAC elevation prompt. procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) # cmd+= " " +params # procHandle, threadHandle, procId, threadId = DoCreateProcess(cmd) if conn: pass conn.put("") if wait: procHandle = procInfo['hProcess'] # print ("pr",prponerocHandle 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 runAsAdmin(cmdLine=None, wait=True): """Attempt to relaunch the current script as an admin using the same command line parameters. Pass cmdLine in to override and set a new command. It must be a list of [command, arg1, arg2...] format. Set wait to False to avoid waiting for the sub-process to finish. You will not be able to fetch the exit code of the process if wait is False. Returns the sub-process return code, unless wait is False in which case it returns None. @WARNING: this function only works on Windows. """ if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.") import win32con import 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:]]) showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' # causes UAC elevation prompt. 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) else: rc = None return rc
def runAsAdmin(cmd_line=None, wait=True, console=True): # TODO: complete description """ Elevates a new python console window to Administrator. 1- cmd_line: 2- wait : 3- cmd : Sets whether the python console should show it's window. It shows the window by default. : True = shows the elevated python console window. : False or None = does not show the elevated python console window. """ if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.\n") python_exe = sys.executable if cmd_line is None: cmd_line = [python_exe] + sys.argv # cmd_line = [cmd, params] elif type(cmd_line) not in (types.TupleType, types.ListType): raise ValueError("cmd_line is not a sequence.\n") cmd = '"%s"' % (cmd_line[0], ) # The path of the cmd window # TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x, ) for x in cmd_line[1:] ]) # The path of the python script that called if console is False: show_cmd = win32con.SW_HIDE else: show_cmd = win32con.SW_SHOWNORMAL # 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. # NOTE: lpVerb='runas' causes UAC elevation prompt. procInfo = ShellExecuteEx(nShow=show_cmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject( procHandle, win32event.INFINITE) # TODO: Necessary? rc = win32process.GetExitCodeProcess(procHandle) else: rc = None return rc
def win_run(command, args, admin=False): """ In windows run a command, optionally as admin. """ if admin: import win32con from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=command, lpParameters=u' '.join('"{}"'.format(arg) for arg in args)) else: return subprocess.Popen([command] + args)
def run_as_admin(*cmd_line, wait=True): verb = "runas" if not cmd_line: cmd_line = [sys.executable] + sys.argv cmd = cmd_line[0] params = " ".join(str(x) for x in cmd_line[1:]) process_info = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=verb, lpFile=cmd, lpParameters=params) if wait: process_handle = process_info['hProcess'] win32event.WaitForSingleObject(process_handle, win32event.INFINITE) return_code = win32process.GetExitCodeProcess(process_handle) else: return_code = None return return_code
def run_vbox_installer_windows(cmd): cmd_dir = '' showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' cmd = cmd.split(" ") installer = cmd[0] args = " ".join(cmd[1:]) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=installer, lpParameters=args) procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) # print "Process handle %s returned code %s" % (procHandle, rc) log.debug("Virtualbox setup finished") return rc
def runAsAdmin(self, cmdLine=None, wait=True): """ Executes the file again as admin. """ python_exe = sys.executable cmdLine = [python_exe] + sys.argv cmd = '"%s"' % (cmdLine[0], ) params = CHANGE_PASSWORD_FILE + self.password.text cmdDir = '' showCmd = win32con.SW_SHOWNORMAL lpVerb = 'runas' procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle)