Run .exe file via Python as Administrator

4

4

i have a problem with starting an .exe.exe file as administrator rights..

I also tried:

subprocess.call(['runas', '/user:Administrator', 'myfile.exe'])

But then i have to enter a password..

Is there any chance to leave that out?

Thanks!

PS: I searched now for some hours... didn't find anything!

Astraioz

Posted 2013-07-04T18:01:07.373

Reputation: 43

Why would you remove the password? – Diblo Dk – 2013-07-04T18:25:30.813

You could use an stdin PIPE to send it, but then you need to store it somehow accessible to your Python script. That looks like proc = subprocess.call(['runas','/user:Administrator','myfile.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) Then you could do proc.stdin.write('password\r\n'). – nerdwaller – 2013-07-04T18:28:04.440

@nerdwaller, I'm trying this for a while but without success. Are you sure this works? – McLeary – 2014-02-11T00:30:36.587

Answers

2

Diblo Dk

Posted 2013-07-04T18:01:07.373

Reputation: 584

2

It's a little roundabout, but another way is to run a shell command, launch Powershell (comes with Windows), then tell Powershell to run the .exe as Admin:

(just remember that the shell command is in CMD, so you escape with backslash, not Powershell's backtick.)

Powershell command: Start-Process "executable.exe" -ArgumentList @("Arg1", "Arg2") -Verb RunAs

CMD running Powershell: Powershell -Command "& { Start-Process \"executable.exe\" ... }"

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

Sam

Posted 2013-07-04T18:01:07.373

Reputation: 139

0

This answer worked for me

import ctypes, sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    # Code of your program here
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)

Iman Kermani

Posted 2013-07-04T18:01:07.373

Reputation: 113

Great solution. I had to add an exit(0) at the end within the else case so that the program doesn't continue down and run the rest of my code. – frakman1 – 2018-12-22T04:47:27.100

0

I realise I'm coming in late on this and it may not be a really elegant solution....but if you open an elevated command prompt and then launched your python script, would the executables called with "subprocess.call" not be launched with the same elevation as the CMD window?

Katey180

Posted 2013-07-04T18:01:07.373

Reputation: 1

No, this does not work. – marsh – 2019-11-22T15:43:43.680