10

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.

Luke Dinkler
  • 731
  • 5
  • 16
  • 36
  • Use `runas`. See, e.g., [this](https://stackoverflow.com/questions/10415653/run-batch-file-as-administrator-windows-7-command-run-as-from-network-file) and, if entering a password on the shell is not an option, [this](https://superuser.com/questions/55809/how-to-run-program-from-command-line-with-elevated-rights) – hlt Aug 28 '14 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. – hlt Aug 28 '14 at 21:03
  • The problem is that this program is going to be distributed, and it obviously can't know the passwords. – Luke Dinkler Aug 28 '14 at 21:05
  • can you not get the user to enter the password? – Padraic Cunningham Aug 28 '14 at 21:24
  • I suppose so. What would the code for runas look like. – Luke Dinkler Aug 28 '14 at 21:39

1 Answers1

10

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)
snowcrash09
  • 4,694
  • 27
  • 45