How to Run Script with Elevated Privilege on Windows

How to run script with elevated privilege on windows

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

How to run a script with elevated privilege on windows?

It looks like types.TupleType and types.ListType do not exist in Python 3. Try the following instead:

elif type(cmdLine) not in (tuple, list)

The value error after saying that "cmdLine is not a sequence" is not exactly accurate because strings are sequences, but should indeed raise a ValueError. I might reword it to "cmdLine should be a non-empty tuple or list, or None." You could update it to more broadly check whether cmdLine is a non-string iterable, but that might be overkill.

I want to run Power Shell script with admin privileges

Some way to run PowerShell with admin privileges:

  1. Search Powershell from the Windows search icon OR click the Windows button from the keyboard --> write Powershell --> You will see the Windows PowerShell --> Right-click on Powershell then click Run as administrator.
  2. Run this command of a PowerShell console: Start-Process powershell -Verb runAs
  3. Run your script from PowerShell like this: PowerShell -f C:\ScriptPath

For more details, you can check this StackOverflow question and answer.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

You can have the script call itself with psexec's -h option to run elevated.

I'm not sure how you would detect if it's already running as elevated or not... maybe re-try with elevated perms only if there's an Access Denied error?

Or, you could simply have the commands for the xcopy and reg.exe always be run with psexec -h, but it would be annoying for the end-user if they need to input their password each time (or insecure if you included the password in the script)...

Opening up Windows Terminal with elevated privileges, from within Windows Terminal

Currently you cannot open an elevated wt.exe session from the command line without workarounds. Workarounds include using gsudo, Using Task Scheduler (I tested this one and it works but you need to use the full path to wt.exe and you can skip the shortcut creation step) OR if you are ok with a keyboard shortcut, the simplest way; using a keyboard shortcut to run Windows Terminal as Admin from the taskbar.

For your use case:

For my specific instance, I simply want to make it simpler to pop open
an admin terminal, I don't need a way to elevate arbitrary commands,
then I will happily use the commands I have already shown here.

The simplest approach will work:

Pin Windows Terminal as the first item on the task bar. Then hit Win+Ctrl+Shift+1 to open it as admin.

If you really must launch Windows Terminal from the command line from within Windows Terminal then create a task in the Task Scheduler:

  1. Give the task a name, check 'Run with highest privileges'.
  2. Choose the 'Actions' tab, click 'New', select 'Start a program' as the action. Put the full path to wt.exe in the 'Program/script field'. Click OK. Click OK again.
  3. Click 'Conditions' tab, uncheck "Start the task only if the computer is on AC power".
  4. Click 'Settings' tab, make sure "Allow task to be run on demand" is checked and uncheck "Stop the task if running for longer than".
  5. Finally in your shell (Powershell), launch an elevated Windows Terminal session by running the command: schtasks /run /TN "TASK_NAME" where TASK_NAME is the name you gave the task in step 1.

Request UAC elevation from within a Python script?

As of 2017, an easy method to achieve this is the following:

import ctypes, sys

def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False

if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

If you are using Python 2.x, then you should replace the last line for:

ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)

Also note that if you converted you python script into an executable file (using tools like py2exe, cx_freeze, pyinstaller) then you should use sys.argv[1:] instead of sys.argv in the fourth parameter.

Some of the advantages here are:

  • No external libraries required. It only uses ctypes and sys from standard library.
  • Works on both Python 2 and Python 3.
  • There is no need to modify the file resources nor creating a manifest file.
  • If you don't add code below if/else statement, the code won't ever be executed twice.
  • You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values here.
  • You can change the display method of the spawned process modifying the sixth parameter.

Documentation for the underlying ShellExecute call is here.

Run Powershell script via batch file with elevated privileges

I have finally ended up with this :

runas.exe /netonly /noprofile /user:domainadm@domain "powershell.exe -
noprofile -File "C:\Users\...\Desktop\Powershell_scripts\New-
ADuser\.ps1" -verb RunAs"

It works like a charm now!

Hope it will help anyone in need. ;)



Related Topics



Leave a reply



Submit