11

I want to run a windows command with Python 3. Like this os.system("echo hi"). However, How about running a command that requires admin access? How do you do this? Thanks.

5
  • Use runas. See, e.g., this and, if entering a password on the shell is not an option, this Commented Aug 28, 2014 at 21:01
  • It's a builtin Windows program that allows you to execute other programs as other users, provided you know their password. See e.g. the first link in my comment. Commented Aug 28, 2014 at 21:03
  • The problem is that this program is going to be distributed, and it obviously can't know the passwords. Commented Aug 28, 2014 at 21:05
  • can you not get the user to enter the password? Commented Aug 28, 2014 at 21:24
  • I suppose so. What would the code for runas look like. Commented Aug 28, 2014 at 21:39

1 Answer 1

11

You can do this with the ShellExecuteEx Win32 API wrapper included in the Pywin32 extensions. If you are using something like ActivePython you may already have the extensions.

To use ShellExecuteEx :

import win32com.shell.shell as shell
commands = 'echo hi'
shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c '+commands)
Sign up to request clarification or add additional context in comments.

8 Comments

Excellent! Can we do this without the pop-up window?
Do you mean the User Account Control pop-up? You're not really supposed to disable that. There are ways around it listed in this question but they all are a bit awkward.
What if we had the user's password?
@LukeDinkler One way for stopping popup : Run your python as admin then execute the scripts. Then automatically all the scripts would have the admin access, and they will not show popups.
This appears to be deprecated in Python 3 and I'm having trouble finding the analogous Python 3 approach.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.