Submitting a password after an input prompt using bash/shell script
Often on machines, you are faced with a script where you have to supply arguments or credentials, but can only do so after an input prompt. This is due to poor coding practice (from the developers) and requires ‘ad-hoc’ solution- one which we try to come up with below.
Expecting — Text after Prompts
The solution comes in the form of
expect. This is available on most Linux systems. We start by spawning our command which generates the prompt, and if the prompt contains a desired keyword or phrase (e.g. ‘Password’) we reply with our return string and a newline (
\n ) character.
The following script runs
<command_to_run> and then enters the first argument (
$1 ) provided to the script.
— Don't forget to make this executable with
chmod a+x <scriptname.sh>
We can now run our code with
./scriptname.sh myNotSoSecurePassword .
Spawning a file you then need to Source
If the script you are interested however produces environmental variables you want to use and is generally sourced using
. ./script or
source ./script then you need to create a new shell, run the expect script and interact with it there.
This can be done as follows :
/usr/bin/expect -f <<EOD
set timeout -1
send "source <script>\n"
expect "<expected string>"
send "<chosen response>\n"
Interactivity and Sourcing
As is seen above, it is possible to open an interactive shell when running
expect directly for a file. However, in certain cases, we may want to supply optional arguments from the parent shell or function.
To do this we need to create a temporary file and feed that into
expect instead. This combines both methods previously mentioned:
#!/bin/bashESCRIPT=`mktemp runner.XXXXXXXXXX` || exit 1cat >$ESCRIPT <<SCRIPT
set timeout -1