- Python Power Move: Run Commands as Admin with These Simple Examples
- User Account Control (UAC)
- Using subprocess
- Using ShellExecute runas
- Using runas in Command Prompt
- Using PowerShell -Verb Runas
- Redirect Output
- Run Python as Admin
- How to Run a Python File as an Administrator on Windows: A Complete Guide
- Creating a Shortcut for Python.exe
- Right-click and Run as Administrator
- How to Run Python Programs ( .py files ) in Windows 10
- Using subprocess.call
- Running an .exe File via Python
- Launching the Python Process as an Administrator
- Deleting a File with Admin Privileges Using Python
- Running a Command or Script as an Admin with Runas
- Checking for Admin Privileges
- Other simple code examples for running a Python file as an administrator on Windows
- Conclusion
Python Power Move: Run Commands as Admin with These Simple Examples
We often find ourselves needing to automate tasks on Windows machine, Although there are many Python libraries out there that supports some common Windows operations and even cross-platforms. It is really hard to substitute Window’s Command Prompt and PowerShell, as they are extremely useful in cases where we need to access different Windows components, configure settings and troubleshooting.
User Account Control (UAC)
Standard user accounts are for day-to-day activities with less permission, while the administrator account has elevated access for all features.
For my personal machine, I’m operating on admin account all time (as the sole user). But Windows, for security reasons, still treats most of my actions as standard account. It only elevates to admin privilege when my operations want to make internal changes to Windows settings and my machine.
The UAC feature when enabled, prompts the user when such action occurred and request for admin access. Additionally, for standard user, it means they need to ask for administrator account login.
When the sign in is an administrator type account | When the sign in is a standard type account |
Now, in terms of task automation in Python, we’ll also want to figure out how to run certain operations with Admin privilege.
Using subprocess
Like most of us, I have been using subprocess to evoke cmd.exe or powershell.exe as desired by passing arguments as list into the function.
import subprocess
def runCmd(*args):
p = subprocess.Popen(
*args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
out, error = p.communicate()
return out, error
But this doesn’t grant the process with admin privilege, and won’t notify us with UAC.
How to achieve this? here are some ways to do it.
Using ShellExecute runas
import ctypes
commands = u’/k echo hi’
ctypes.windll.shell32.ShellExecuteW(
None,
u»runas»,
u»cmd.exe»,
commands,
None,
1
)
runas from the Windows API launches an application as Administrator. User Account Control (UAC) will prompt the user for consent to run the application elevated or enter the credentials of an administrator account used to run the application.
What about a more pythonic approach?
Using runas in Command Prompt
runas application runs command as a different user; it is most commonly used but not limited to perform operation with administrator account for granting admin access.
Note: the password is handled outside UAC, which may not be the desired behavior
command = [‘cmd.exe’, ‘/c’, ‘runas’, ‘/user:administrator’, ‘regedit’]
p = subprocess.Popen(command, stdin=subprocess.PIPE)
p.stdin.write(‘password’)
p.communicate()
Using PowerShell -Verb Runas
This is my preferred method, since it is most flexible and also evokes UAC for admin access.
Start-Process -argumentlist -Verb Runas
& {Start-Process -argumentlist -Verb Runas}
Start-Process -ExecutionPolicy Bypass -File
It is very obvious from the above example, we can basically use PowerShell to wrap around anything, including Command Prompt.
Start-Process cmd.exe -argumentlist ‘/k «dir»‘ -Verb Runas
To bundle everything together, a working example would look like this in Python:
ps_command = «& {{Start-Process cmd.exe -argumentlist ‘/k \»dir\»‘ -Verb Runas}}»
command = [‘powershell.exe’, ‘-command’, ps_command]
runCmd(command)
essentially using subprocess to run PowerShell in admin using -Verb Runas to execute command /k dir in Command Prompt (which also has elevated access).
Redirect Output
By doing the above, we are running an executable within a process. the sacrifice is that it is difficult to pass the output, but here’s a few workarounds:
Output results to a file
Start-Process cmd.exe -argumentlist ‘/c «dir»‘ -redirectStandardOutput «C:\Users\xlei\Desktop\temp.txt»
Output result to the console
$output = Start-Process cmd.exe -argumentlist ‘/c «dir»‘ -PassThru -Wait
$output.ExitCode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function Start-ProcessWithOutput
{
param ([string]$Path,[string[]]$ArgumentList)
$Output = New-Object -TypeName System.Text.StringBuilder
$Error = New-Object -TypeName System.Text.StringBuilder
$psi = New-object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = $Path
if ($ArgumentList.Count -gt 0)
{
$psi.Arguments = $ArgumentList
}
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
[void]$process.Start()
do
{
if (!$process.StandardOutput.EndOfStream)
{
[void]$Output.AppendLine($process.StandardOutput.ReadLine())
}
if (!$process.StandardError.EndOfStream)
{
[void]$Error.AppendLine($process.StandardError.ReadLine())
}
Start-Sleep -Milliseconds 10
} while (!$process.HasExited)
#read remainder
while (!$process.StandardOutput.EndOfStream)
{
#write-verbose ‘read remaining output’
[void]$Output.AppendLine($process.StandardOutput.ReadLine())
}
while (!$process.StandardError.EndOfStream)
{
#write-verbose ‘read remaining error’
[void]$Error.AppendLine($process.StandardError.ReadLine())
}
return @{ExitCode = $process.ExitCode; Output = $Output.ToString(); Error = $Error.ToString(); ExitTime=$process.ExitTime}
}
$p = Start-ProcessWithOutput cmd.exe -argumentlist ‘/c «dir»‘
$p.ExitCode
$p.Output
$p.Error
Run Python as Admin
Running the whole python script in Admin, meaning that the subsequent processes will have admin access, if this is the behaviour you prefer.
How to Run a Python File as an Administrator on Windows: A Complete Guide
Learn how to run a Python file as an administrator on Windows with step-by-step instructions, code examples, and best practices. Access system files and settings with ease.
- Creating a Shortcut for Python.exe
- Right-click and Run as Administrator
- How to Run Python Programs ( .py files ) in Windows 10
- Using subprocess.call
- Running an .exe File via Python
- Launching the Python Process as an Administrator
- Deleting a File with Admin Privileges Using Python
- Running a Command or Script as an Admin with Runas
- Checking for Admin Privileges
- Other simple code examples for running a Python file as an administrator on Windows
- Conclusion
- How do I run a file as administrator?
- What is %run in Python?
- How do I run a subprocess as admin in Python?
As a programmer or developer, you may need to run a Python file as an administrator on a Windows operating system to access system files and settings. In this post, we will explore various ways to run a Python file as an administrator on Windows and provide helpful tips and best practices.
Creating a Shortcut for Python.exe
One way to run a Python file as an administrator is to create a shortcut for python.exe and change the shortcut target to include the file path for your Python script. Here are the steps to follow:
- Right-click on the desktop and select “New” -> “Shortcut”.
- In the “Create Shortcut” window, type “python.exe” and click “Next”.
- In the next window, type the file path for your Python script, enclosed in double quotes, after the path for python.exe. For example, if your Python script is located in the “C:\Users\Username\Documents\Python Scripts” folder and is named “myscript.py”, the target should look like this:
"C:\Users\Username\AppData\Local\Programs\Python\Python39\python.exe" "C:\Users\Username\Documents\Python Scripts\myscript.py"
Now when you double-click on the shortcut, the Python script will run as an administrator.
Right-click and Run as Administrator
Another way to run a Python script as an administrator is to right-click the .py file and select “Run as Administrator.” Here are the steps to follow:
- Locate the Python script you want to run.
- Right-click on the script and select “Run as Administrator”.
Now the Python script will run as an administrator.
How to Run Python Programs ( .py files ) in Windows 10
In this tutorial you will learn How to run Python Programs ( .py files ) on windows 10 computer Duration: 8:07
Using subprocess.call
If you are an administrator, you can take ownership and grant yourself whatever permissions you need to run the script using subprocess.call. Here’s an example:
import subprocesssubprocess.call(["runas", "/user:Administrator", "python", "myscript.py"])
In this example, “Administrator” is the name of the administrator account, and “myscript.py” is the name of the Python script you want to run.
Running an .exe File via Python
A roundabout way to run an .exe file via Python as an administrator is to run a shell command, launch PowerShell, and then tell PowerShell to run the .exe as admin. Here are the steps to follow:
powershell Start-Process 'C:\path\to\your\exe' -Verb RunAs
In this command, replace “C:\path\to\your\exe” with the actual path to the .exe file you want to run.
Launching the Python Process as an Administrator
There are various ways to launch the Python process as an administrator depending on how you start the script. Here’s an example:
import ctypes import osdef is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return Falseif is_admin(): os.system('myscript.py') else: ctypes.windll.shell32.ShellExecuteW(None, "runas", "python", "myscript.py", None, 1)
In this example, the script first checks if the user has admin privileges using the is_admin() function. If the user has admin privileges, the script runs as usual. If not, the script is relaunched using the ctypes.windll.shell32.ShellExecuteW() function, which prompts the user for admin credentials and then launches the script as an administrator.
Deleting a File with Admin Privileges Using Python
To delete a file with admin privileges using Python, you may have to run code that runs standard move or remove with admin privileges. Here’s an example:
import osos.system('takeown /f "C:\path\to\your\file" /r /d y') os.system('icacls "C:\path\to\your\file" /grant administrators:F /t') os.remove("C:\path\to\your\file")
In this example, replace “C:\path\to\your\file” with the actual path to the file you want to delete.
Running a Command or Script as an Admin with Runas
To run a command or script as an admin, you can use runas, a command that runs a command as a different user, commonly used to perform operations with an administrator account. Here are the steps to follow:
runas /user:Administrator "command or script path"
In this command, replace “Administrator” with the name of the administrator account, and “command or script path” with the actual path to the command or script you want to run.
Checking for Admin Privileges
To run a Python file as an admin, you can use is_admin() to check if the user has admin privileges and use ctypes.windll.shell32.IsUserAnAdmin() to return a boolean value indicating if the user has admin privileges. Here’s an example:
import ctypesdef is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return Falseif is_admin(): print("You have admin privileges.") else: print("You do not have admin privileges.")
Other simple code examples for running a Python file as an administrator on Windows
In Python case in point, run file as administrator python code sample
# Run file as administrator on Windows 7, 8, 10 # Tested for Python 3.8.5 import osdef RunAsAdmin(path_to_file,*args): os.system(r'Powershell -Command "Start-Process "'+path_to_file+'"'+ # CMD running Powershell ' -ArgumentList @('+str(args)[1:-1]+')'+ # Arguments. [1:-1] to remove brackets ' -Verb RunAs"' # Run file as administrator )RunAsAdmin('cmd.exe','arg1','arg2')
Conclusion
Running a Python file as an administrator on Windows is a necessary task when you need to access system files and settings. With various methods available such as creating a shortcut for Python.exe, right-clicking and running as administrator, using subprocess.call, running an .exe file via Python, launching the Python process as an administrator, deleting a file with admin privileges using Python, running a command or script as an admin with runas, and checking for admin privileges, you can choose the method that works best for you. Always take the necessary precautions and follow the best practices when running a Python file as an administrator on Windows.