Run script as administrator python

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.

Читайте также:  Webview with javascript android

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.

admin
When the sign in is an administrator type account
std
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 python script as administrator

If you define HKCR\Python.File\shell\runas\command in the registry, then you can launch the script elevated via os.startfile(__file__, ‘runas’) . Just copy the command from HKCR\Python.File\shell\open\command . The user will get a UAC prompt to elevate. Test to see whether it’s necessary by calling ctypes.windll.shell32.IsUserAnAdmin() . For passing command-line arguments you’ll have to use ShellExecuteEx instead, via ctypes or PyWin32, as linked above.

I resolve my issue by looking into one of the topics on stackoverflow.com It suggested to use batch file which will call python script and on the top of that batch use PowerShell command to elevate privilage. It worked for me. Ticket could be closed

1 Answer 1

If you don’t know the administrator password then you cannot execute your python script with elevated privilege!

Reason: The solutions available for executing the python script with elevated privilege will simply prompt the UAC. Then you have to provide the administrator password and if the password is correct your script will execute with administrator privilege. So, ultimately you must know the administrator password!

Also the reason why you need an administrator password is that it would be a security risk that you can execute any script with administrator privilege without having the administrator rights. Just think if any one can execute any script on your computer from the guest account. Hope it helped.

Источник

How To Run Python Script As Admin With Code Examples

In this session, we’ll attempt our hand at fixing the How To Run Python Script As Admin puzzle by utilizing the pc language. The code that’s displayed under illustrates this level.

import ctypes, sys def is_admin(): attempt: return ctypes.windll.shell32.IsUserAnAdmin() besides: return False if is_admin(): # Code of your program right here else: # Re-run this system with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".be part of(sys.argv), None, 1)

We have offered a wealth of illustrative examples to point out how the How To Run Python Script As Admin drawback may be solved, and we’ve additionally defined how to take action.

How do I run a Python script with out admin rights?

Install Python It may be put in with out directors rights by means of a software program named Miniconda. Download miniconda from https://conda.io/miniconda. Make positive to decide on the Python 3.7 model for Windows. If you do not know in case your system is 32-bit or 64-bit, decide 32-bit.

How do I run a batch file as Administrator in Python?

Use the runas Command to Run the Batch File as Administrator If the Batch file incorporates a specific line or a set of traces that requires administrative privileges, you should use the runas command to run a specific line in admin mode.02-Jun-2022

How do I get Administrator permission in Python?

“python get admin permission” Code Answer

  • import ctypes, sys.
  • def is_admin():
  • attempt:
  • return ctypes. windll. shell32. IsUserAnAdmin()
  • besides:
  • return False.
  • if is_admin():
  • # Code of your program right here.

How do I run a Python script from the command line?

To run Python scripts with the python command, you could open a command-line and kind within the phrase python , or python3 when you have each variations, adopted by the trail to your script, identical to this: $ python3 howdy.py Hello World! If every part works okay, after you press Enter , you will see the phrase Hello World!

How do I run a Python script with out the code?

@echo off will mainly cover all of the steps and simply present the output. Line 2: name is used for calling the conda command immediate after which operating it by means of the activate. bat file. Line 4: The Python file information.py is being run at this second within the command immediate and an finish loop is began till the output comes.23-Mar-2021

Does pip require admin rights?

Installing python packages utilizing pip (no admin proper required)21-Aug-2020

How do I run a file as administrator?

Select the file and press CTRL + Alt + Enter to open properties. Alternatively, merely right-click and choose properties. In the compatibility tab, allow Run this program as an administrator. In the case of shortcuts, allow it from Shortcut > Advanced > Run as administrator as an alternative.01-Apr-2022

How do I run a batch file as administrator?

If you want to routinely elevate a Batch File and make it run as Administrator, comply with these steps:

  • Locate the Batch file.
  • Right-click on the Batch file.
  • Select Create Shortcut.
  • Give it an acceptable identify.
  • Now right-click the shortcut file.
  • Click Properties.
  • Select Shortcuts tab > Advanced.
  • Select Run As Administrator field.

How do I run as administrator mode?

Press and maintain down the SHIFT key whilst you right-click the executable file or the icon for the applying, after which choose Run as. Select The following person. In the User identify and Password packing containers, kind the administrator account and password, after which choose OK.24-Sept-2021

How do I run a command immediate as Administrator?

Using the run command To accomplish that, open a run-box, write cmd , and press Control + Shift + Enter to open the command immediate as an administrator.

Build with us Share this content

Источник

Оцените статью