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.
Asked
Active
Viewed 2.4k times
10
-
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 Answers
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
-
-
Do you mean the [User Account Control](http://en.wikipedia.org/wiki/User_Account_Control) pop-up? You're not really supposed to disable that. There are ways around it listed in [this question](http://superuser.com/questions/200788/how-to-run-an-app-as-administrator-without-the-prompt) but they all are a bit awkward. – snowcrash09 Aug 29 '14 at 08:36
-
-
1
-
-
1@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. – Deepak Yadav Oct 01 '20 at 08:27
-
-
1This appears to be deprecated in Python 3 and I'm having trouble finding the analogous Python 3 approach. – Bernd Wechner Nov 17 '22 at 02:59