script icon indicating copy to clipboard operation
script copied to clipboard

How do I automate inputs to interactive programs?

Open danielporto opened this issue 2 years ago • 4 comments

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

danielporto avatar Nov 28 '22 09:11 danielporto

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

bitfield avatar Nov 28 '22 10:11 bitfield

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.

bitfield avatar Nov 28 '22 14:11 bitfield

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?

ryan-n-may avatar Jun 30 '23 04:06 ryan-n-may

I think the latter; try sudo -S (which tells it to read from stdin).

bitfield avatar Jun 30 '23 09:06 bitfield