Run process as admin with subprocess.run in python

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

Leave a Comment