Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run script with elevated privilege on windows

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.

like image 637
sundar_ima Avatar asked Oct 30 '13 01:10

sundar_ima


People also ask

How do you run a script with elevated privileges?

The easiest way to start elevated Powershell windows is by searching for the Powershell application. Press the Windows button to open the start menu and type Powershell. Select Run as administrator to launch run a Powershell window with full privileges. Press Yes in the UAC prompt, and you are good to go!

How do I run an elevated privilege in Windows 10?

How Do I Get Full Administrator Privileges On Windows 10? Search settings, then open the Settings App. Then, click Accounts -> Family & other users. Finally, click your user name and click Change account type – then, on the Account type drop-down, select Administrators and click OK.

How do I force a script to run as administrator?

To automatically run the PowerShell script as administrator, create a shortcut to your PowerShell console on your desktop. Enable “Run as Administrator” and click on “OK” button.


2 Answers

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() 

The actual code is:-

#!/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()) 
like image 105
sundar_ima Avatar answered Oct 06 '22 13:10

sundar_ima


in comments to the answer you took the code from someone says ShellExecuteEx doesn't post its STDOUT back to the originating shell. so you will not see "I am root now", even though the code is probably working fine.

instead of printing something, try writing to a file:

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" 

and then look in the file.

like image 27
andrew cooke Avatar answered Oct 06 '22 14:10

andrew cooke