TrampolineTales
TrampolineTales

Reputation: 826

How can I automatically respond to a password prompt via the command line?

I'm looking to respond to a password prompt in the linux terminal. I know how to do this with echo and a non-password prompt. For example, let's say whatsyourname.sh prompted me for a string with my name after being ran, but didn't allow my name to be passed as an argument in the inital command. I would do the following:

echo -e "dan" | ./whatsyourname.sh

However, if I ran a command that asked me for a password after being ran, the following does not work:

echo -e "supersecurepassword" | sudo apt-get update

I'm guessing this has something to do with the fact that the characters are hidden while a password is being input in the command line. How would I respond to a password prompt within the inital command?

Upvotes: 7

Views: 10316

Answers (1)

rowan
rowan

Reputation: 461

You're looking for sudo -S

Explaining -S - man sudo

-S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.

Simple,

#!/bin/bash
echo "notsecure" | sudo -S apt-get update

Variable,

#!/bin/bash
pass="notsecure"
echo $pass | sudo -S apt-get update

Lets still type it,

#!/bin/bash
read -s -p "[sudo] sudo password for $(whoami): " pass
echo $pass | sudo -S apt-get update

Explaining -s and -p - help read

-r do not allow backslashes to escape any characters

-s do not echo input coming from a terminal

Handy if you make a script that logs into multiple servers to view route -n for example.

Upvotes: 5

Related Questions