I\'ve managed to get the cmd being opened by python. However, using runas administrator comes with a password check before cmd.exe is executed.
I\'m using this to op
This piece of code actually works (tested on a Windows 2008 server). I've used it to call runas
for a different user and pass his password. A new command prompt opened with new user context, without needing to enter password.
Note that you have to install pywin32
to have access to the win32 API.
The idea is:
Popen
the runas
command, without any input redirection, redirecting outputwin32
packages, with the final \r
to end the password input.(adapted from this code):
import win32console, win32con, time
import subprocess
username = "me"
domain = "my_domain"
password ="xxx"
free_console=True
try:
win32console.AllocConsole()
except win32console.error as exc:
if exc.winerror!=5:
raise
## only free console if one was created successfully
free_console=False
stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
p = subprocess.Popen(["runas",r"/user:{}\{}".format(domain,username),"cmd.exe"],stdout=subprocess.PIPE)
while True:
if p.stdout.read(1)==":":
for c in "{}\r".format(password): # end by CR to send "RETURN"
## write some records to the input queue
x=win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
x.Char=unicode(c)
x.KeyDown=True
x.RepeatCount=1
x.VirtualKeyCode=0x0
x.ControlKeyState=win32con.SHIFT_PRESSED
stdin.WriteConsoleInput([x])
p.wait()
break