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!

  • Why would you remove the password? – Diblo Dk Jul 4 '13 at 18:25
  • 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 Jul 4 '13 at 18:28
  • @nerdwaller, I'm trying this for a while but without success. Are you sure this works? – McLeary Feb 11 '14 at 0:30
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 } " '''
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?

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)
  • 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 Dec 22 '18 at 4:47

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.