Question

This is my simple bash:

cat test.sh

#!/bin/bash 
echo "hello"
su - root -c /path/to/script.sh <<EOF
password                              
EOF
whoami
echo "good bye"

But I get this error:

./test.sh
hello
su: must be run from a terminal
<current-user>
good bye

(OR)

cat test2.sh
#!/bin/bash 
echo "hello"
sudo su <<EOF
password                              
EOF
whoami
echo "good bye"

Again another error

(OR)

cat test3.sh
#!/bin/bash 
echo "hello"
su root <<EOF
password                              
EOF
whoami
echo "good bye"

again error...

when I try:

#!/bin/bash
echo "hello"
sudo -s <<EOF
<password>
echo Now I am root
id                                                                      
echo "yes!"
EOF
whoami
echo "good bye"

Then the output is:

./script.sh
hello
[sudo] password for <user>:

I also changed my script to:

#!/usr/bin/expect -f
spawn sudo -s <<EOF
expect "assword for user:"
send -- "password\r"                                                                      
expect eof

and output is:

spawn sudo -s <<EOF
[sudo] password for user: 
/bin/bash: <<EOF: command not found

Also which sh output is /bin/sh

How can I resolve the error in these three scripts?

Était-ce utile?

La solution

Doing this kind of stuff is not safe or standard practice (in fact many consider it disasterous), it is really not a good idea to put a password in a script. A more standard approach would be simply to expect the whole script to be executed with root privileges, or just to have the script prompt for a password. You can also allow various commands to be run via sudo without a password by particular users by using the NOPASSWD option in /etc/suoders.

However, now that you are aware of the risks, it is possible to use sudo -kS to have sudo read the password from stdin:

sudo -kSs << EOF
password
whoami
echo "Not a good idea to have a password encoded in plain text"
EOF
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top