file: test.sh
who
su superuser <<BELUGA
mysuperpassword
BELUGA
who
$ ./test.sh
just waits for input. What am I doing wrong? Is there a way to automate this?
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityYou want to use the "expect" command for passing your username and password.
Note however that what you want to do there smells like a bad approach. Maybe we can halp you better if you elaborate a little more on your original problme you want to solve.
I think it would be a lot better to install/use sudo an with a configuration config that allows NOPASSWD for the specific action you are trying to automate.
It will be much safer to allow a specific command via sudo then it would be to store your root password in a text file somewhere.
Running a script as a user and having it upgrade its permissions to root is probably a bad idea. A better solution would be to run the script as root and have it downgrade its permissions as necessary:
#!/bin/sh
UN=user
whoami
sudo -u $UN whoami
When run as root (assuming user
is a valid user) the output should be this:
root
user
However if you really want to have a script run as a user and be able to execute commands as root, there are 2 options that I know of.
Use sudo with stored password:
#!/bin/sh
whoami
sudo -S -p "" whoami <<EOF
mysuperpassword
EOF
Which will output (when run as 'user'):
user
root
Use sudo with no password.
Add a list of the commands that you wish to run into the /etc/sudoers
file by running visudo
as root. For example, to allow user
to run the commands apache2ctl
and whoami
, add the following:
User_Alias SPECIAL = user
Cmnd_Alias SPECIAL_COMMANDS = /usr/sbin/apache2ctl, /usr/bin/whoami
SPECIAL ALL = NOPASSWD: SPECIAL_COMMANDS
Or if you really trust user
, if it's you for example, you can allow the user to execute any command without a password:
user ALL=(ALL) NOPASSWD: ALL
Then when the following script is run by user
:
#!/bin/sh
whoami
sudo whoami
It will output:
user
root
su
'd command.)