Federico Pinciaroli
Federico Pinciaroli

Reputation: 163

Running batch file as Administrator in python

I'm tryng to run a batch file in python with administrator privileges using runas command.

My code is:

prog = subprocess.Popen(['runas', '/noprofile', '/user:Administrator', ' c:\windows\system32\addtask.bat'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)
prog.stdin.write('mypass\n')
prog.stdin.flush()
output, error = prog.communicate()
if prog.returncode != 0: 
    print("FAILED: %d %s - %s" % (prog.returncode, output, error))

but it doesn't work. It outputs:

FAILED: 1 Enter the password for Administrator: - none

I think there's something wrong passing the password through stdin.

Any suggestions?

Upvotes: 2

Views: 6295

Answers (1)

djvg
djvg

Reputation: 14255

The question does not state if the password must be entered programmatically.

If you don't mind entering the password manually, via UAC prompt, you could run the bat file using cmd.exe, and use ShellExecuteW to request elevation.

For example:

from ctypes import windll

bat_file_path = 'c:\windows\system32\addtask.bat'  # from OP
result = windll.shell32.ShellExecuteW(
    None,  # handle to parent window
    'runas',  # verb
    'cmd.exe',  # file on which verb acts
    ' '.join(['/c', bat_file_path]),  # parameters
    None,  # working directory (default is cwd)
    1,  # show window normally
)
success = result > 32

Upvotes: 2

Related Questions