script
script copied to clipboard
How do I automate inputs to interactive programs?
Every so often, I need to automate tasks that need to provide answers to interactive programs For instance, to simulate user's sessions or just because the program does not provide a non-interactive interface. Normally, I use "expect" for that (ex: https://phoenixnap.com/kb/linux-expect)
How can the same feature be implemented with go script? Thanks
If the program reads from standard input, then running it via Exec
will pass it the contents of the pipe as though the user had typed it on the terminal:
script.Echo("hello").Exec("cat").Stdout()
// Output:
// hello
Note that this probably won't work for programs which ignore their process's configured standard input stream, and read directly from the terminal device, as some do to avoid echoing characters (when typing passwords, for example). If you have a use case like that, I'd be interested to hear about it.
Hello,
script.Echo("Password").Exec("sudo apt-get update").Tee().Wait()
Doesn't seem to work for sudo password. Maybe this is a good thing, however, this operation doesn't work either:
script.Echo("Y").Exec("sudo apt-get remove python3").Tee().Wait()
Is this an error on my part or an example of a program reading directly from the terminal device?
I think the latter; try sudo -S
(which tells it to read from stdin).