Feeding input to an interactive command line application Feeding input to an interactive command line application powershell powershell

Feeding input to an interactive command line application


you need to create an usual text file like

connect myvpnhost
myloginname
mypassword

save it as myfile.dat (for example) and then call

"%ProgramFiles%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" -s < myfile.dat


There are at least two ways to read input in a Windows console application.

  • ReadConsole: reads input either from keyboard or redirection (documentation).
  • ReadConsoleInput: reads only raw keystrokes (documentation).

The vpncli.exe application uses ReadConsoleInput in order to read the password, that's way redirecting the password does not work. You can, though, use WriteConsoleInput. I have a small Python script that does exactly that:

import subprocessimport win32consoleANYCONNECT_BIN = 'c:\\Program Files\\Cisco\\Cisco AnyConnect Secure Mobility Client\\vpncli.exe'def write_console_input(text):  stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)  ir = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)  ir.KeyDown = True  for ch in text:    ir.Char = unicode(ch)    stdin.WriteConsoleInput([ir])def main():  proc = subprocess.Popen([ANYCONNECT_BIN,'connect','VPN'],stdin=subprocess.PIPE)  proc.stdin.write('%s\n%s\n' % ('GROUP', 'USERNAME'))  write_console_input('%s\n' % 'PASSWORD')  ret = proc.wait()  print retif __name__ == '__main__':  main()