11

Is there a way of passing some runas=True arg to a subprocess.run function in python? I want to run a process as admin (elevate it). Thanks for answers :)\

EDIT: Using Windows OS.

Jakub Bláha
  • 1,301
  • 2
  • 19
  • 40

2 Answers2

20

since OS is not specified, I will take the example of MS Windows OS

Windows has a command line utility "Run as", which can be used as

  runas [{/profile | /noprofile}] [/env] [{/netonly | /savecred}] [/smartcard] [/showtrustlevels] [/trustlevel] /user:<UserAccountName> "<ProgramName> <PathToProgramFile>"

for further reference https://technet.microsoft.com/en-us/library/cc771525.aspx

You can use this in code like below

import subprocess as sp

prog = sp.Popen(['runas', '/noprofile', '/user:Administrator', 'NeedsAdminPrivilege.exe'],stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()
greybeard
  • 2,102
  • 7
  • 24
  • 58
pankaj mishra
  • 2,382
  • 2
  • 14
  • 30
0

If you want to run a command as the same user but with admin privilege

Please refer to this solution:

os.system(r'''
Powershell -Command "& { Start-Process \"notepad.exe\"
 -ArgumentList @(\"C:\\Windows\\System32\\drivers\\etc\\hosts\")
 -Verb RunAs } " '''

The original answer can be found here https://superuser.com/a/753600/1088510

ZMJ
  • 159
  • 1
  • 10