To automate commands, I have used over the years expect. It is great to simulate an interactive session, either when dealing with stubborn commands that do require interactivity, or to interact with active devices or other servers on your network. I still use it to login to active equipment, and fetch some statistics and perform automatic backups.
Expect is a program that "talks" to other interactive programs
according to a script. Following the script, Expect knows what can be
expected from a program and what the correct response should be. An
interpreted language provides branching and high-level control
structures to direct the dialogue. In addition, the user can take
control and interact directly when desired, afterward returning
control to the script.
Using Expect Scripts to Automate Tasks
As an example, a expect script I wrote to test the POP service:
#!/bin/sh
# \
exec expect "$0" ${1+"$@"}
set force_conservative 0 ;# set to 1 to force conservative mode even if
;# script wasn't run conservatively originally
if {$force_conservative} {
set send_slow {1 .1}
proc send {ignore arg} {
sleep .1
exp_send -s -- $arg
}
}
set timeout -1
spawn telnet 127.0.0.1 110
match_max 100000
expect {
"Hello" { send -- "USER [email protected]\r"; exp_continue
}
"assword" { send -- "PASS password\r" ; exp_continue
}
"logged" {
send -- "LIST 1\r" ; exp_continue
}
-re "failed|denied" { exit
}
"OK 1" { send -- "QUIT\r"; }
}
As per my conversation bellow with @cas, I would also point out, that the simple regexp expect language subset is useful for short automations scripts/[very] rough prototypes, together with bash.
If there is a need to more convoluted handling of output, the interactive handling can/better be done with another programming language.
For instance, in python, pexpect, or even in C, using libexpect or miniexpect.
Lately with the devops movement, you also have got a whole host of new [and old] frameworks to automate system tasks such as Ansible, Puppet, Salt.
They do require however a learning curve, and more resources. I personally favor Ansible.
Ansible Tip: Running Interactive Scripts with Ansible