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>

#!/bin/bash/usr/bin/expect <<EOD
spawn <command_to_run>
expect "Password"
send "$1\n"
expect eof
EOD

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 :

#!/bin/bash
/usr/bin/expect -f <<EOD
set timeout -1
spawn /bin/bash
send "source <script>\n"
expect "<expected string>"
send "<chosen response>\n"
interact
EOD

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
spawn /bin/bash
send "source <script>\n"
expect "<expected string>"
send "$1\n"
interact
SCRIPT
/usr/bin/expect -f $ESCRIPT

An additional merit to this, is that we can then compile the shell script and mask the contents of our file — see below.

Compiling the script

If we wish to obfuscate the code within our script we can compile it to binary using the shc command. This process is explained in:

Disclaimer

This should solve any problems you might have, but remember that storing passwords as plaintext will always be a bad idea!

Research Software Engineer specialising in Data Visualisation with a touch of HPC. — PhD in Atmospheric Chemistry and Masters in Theoretical Physics.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store