4

My shell script (don't have EXPECT, and is not possible) runs a shell script impersonating another user. Let's say the following script is named toto1.sh and is run with a user called MYUSERNAME1.

#!/bin/sh
su - MYUSERNAME2 ./app/sh/toto2.sh

My script stops, prompting a password request...

How can I send the password for MYUSERNAME2?

simlev
  • 3,912
ercey
  • 41

2 Answers2

4

If you have sudo available, the solution has already been posted in a number of places:

echo <password> | sudo -S -u <user> <command>

From 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.

simlev
  • 3,912
2

Approach 1 - Read from file

You can save the password in a read-only file for the user and pass the contents to the sudo command.

This will avoid password being stored in shell history

# Save the password in the hidden file
echo "password" > ~/.password

Update the permissions to allow only the user to read it

chmod 400 ~/.password

Pass the password over STDIN to sudo

☠ cortex ☠ [~] cat ~/scripts/login_file.sh cat ~/.password | sudo -S su

Execute the script

☠ cortex ☠ [~] bash ~/scripts/login_file.sh [sudo] password for cortex: ☠ cortex ☠ [~]

Approach 2 - Save to temporary environment variable

With this approach, you need to enter on the shell or in the script.

☠ cortex ☠ [~] cat ~/scripts/login.sh 
my_password='password'                  # SET PASSWORD
echo "$my_password" | sudo -S su        # INVOKE sudo WITH PASSWORD

Combine with the script

Use any of the approaches mentioned above and authenticate sudo Then invoke the commands with root access.

☠ cortex ☠ [~] cat ~/scripts/login.sh 
# SET PASSWORD
my_password='password'

INVOKE sudo WITH PASSWORD

echo "$my_password" | sudo -S su;

INVOKE COMMANDS WITH ROOT ACCESS

sudo -i <<'EOF' echo "Now i am $(whoami)" echo "$(id)" EOF

☠ cortex ☠ [~] bash ~/scripts/login.sh [sudo] password for cortex: Now i am root uid=0(root) gid=0(root) groups=0(root)

Cut the clutter with ALIAS

Make the sudo to internally get the password and authenticate itself. You need not require to input the password over STDIN every time

# Create the alias with the Approach 1
☠ cortex ☠ [~] echo "alias sudo=\"cat ~/.password | sudo -S\"" >> ~/.bashrc

OR Create the alias with the Approach 2

☠ cortex ☠ [~] echo "alias sudo=&quot;echo &quot;password&quot; | sudo -S&quot;" >> ~/.bashrc

Re-load the environment

☠ cortex ☠ [~] . ~/.bashrc

Use sudo directly - No need to pass on password everytime

☠ cortex ☠ [~] sudo whoami root