See Expect. The Expect programming language
(and the perl Expect module that provides that functionality
to Perl users) are designed
percisely for doing what you want: interacting with console and command-line
processes like it was a user at a keyboard.