8
votes

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.

1
Use runas. See, e.g., this and, if entering a password on the shell is not an option, this - hlt
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
The problem is that this program is going to be distributed, and it obviously can't know the passwords. - Luke Dinkler
can you not get the user to enter the password? - Padraic Cunningham
I suppose so. What would the code for runas look like. - Luke Dinkler

1 Answers

7
votes

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)