1

I'm trying to make a shell script which asks the user in the beginning for a password and then stores it in a variable so it may be used each time the script requires root access.

My thought was to do something like this:

read -s "Please enter your password: " PASSWORD

echo -e $PASSWORD | su -c 'do some root action here'

But that is not working. How could this be accomplished?

EDIT Ok so I've started to investigate expect and this is what I've got so far:

#!/usr/bin/env bash

user=$(whoami)

echo "Pleas enter your root password. [Followed by Enter]"
read -s "Password:" PASSWORD

/usr/bin/expect <<EOD
spawn su -c 'echo \"$user ALL=(ALL) ALL\" >> /etc/sudoers'
expect "Password:"
send $PASSWORD
interact
EOD

So this isn't working but the output I get from the terminal looks like I'm getting closer to my goal.

Is anyone able to help me solve this?

Thank you.

Villi Magg
  • 1,163
  • 3
  • 13
  • 23
  • 4
    `su` and most other utilities that prompt for a password don't accept the password on stdin, they accept it from the tty. You'll have to use `expect` if you want to feed passwords to them. – Celada Apr 29 '13 at 22:23
  • 2
    If the script is going to be interactive anyway, consider just using `sudo` and letting `sudo` handle the password. – btanaka Apr 29 '13 at 22:25
  • @StevenPenny, let me rephrase my question then, and you can vote my question up again then. – Villi Magg Apr 29 '13 at 22:35
  • @Celada, do you know a quick and easy way to accomplish this using expect? I've been trying to follow that guide on expect and I don't see how it's supposed to be used in a case like this. Thank you! – Villi Magg Apr 29 '13 at 22:37
  • @btanaka sudo doesn't work for ```echo "username ALL=(ALL) ALL" >> /etc/sudoers``` – Villi Magg Apr 29 '13 at 23:43
  • 1
    @VilliMagg I was unclear. I meant: "Why not just write your script to do what you want it to do, then run *your script* with sudo? – btanaka Apr 30 '13 at 01:48

0 Answers0