Reputation: 169
I have a shell script as given below.
#!/bin/bash
sudo -u testuser -H sh -c "
mkdir /usr/local/testdir;
if [ $? -eq 0 ];then
echo "Successfull";
else
echo "Unsuccessfull";
fi
"
I have given privileges to user testuser to execute shell script with sudo, but without asking password.For this I add the below line in /etc/sudoers
file,
testuser ALL=(ALL) NOPASSWD: ALL
And it works fine that, I could run commands with sudo, but without asking password. But the above shell script always giving out put ass follows,
mkdir: cannot create directory `/usr/local/testdir': Permission denied
Successfull
And it is not creating directory testdir
inside /usr/local
. Please advice me what modification shall I need to do to work this script fine.
Thanks.
Upvotes: 2
Views: 10015
Reputation: 63902
Two problems:
1.) You told:
sudo -u testuser -H ...
what's mean: run the command as testuser
, and he doesn't has permissions to write into the /usr/local
therefore you getting permission denied
.
When you remove the -u testuser
, the command will run as root (as default) (without password for the testuser
) and will create the directory.
Seems, you simply misunderstand how the sudo
and /etc/sudoers
works. The -u user
mean
-u user' The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a user name, #uid. When running commands as a uid, many shells require that the '#' be escaped with a backslash ('\'). Security policies may restrict uids to those listed in the password database. The sudoers policy allows uids that are not in the password database as long as the targetpw option is not set. Other security policies may not support this.
2.) second problem the Successfull
message.
You're using double quotes for sh -c
. The Variable expansion
is done BEFORE the sh -c
even starts. So use single quotes, and will get the correct Unsuccessfull
message:
sudo -u testuser -H sh -c '
mkdir /usr/local/testdir
if [ $? -eq 0 ];then
echo "Successfull";
else
echo "Unsuccessfull";
fi
'
and use the next as a solution:
sudo -H sh -c '
mkdir /usr/local/testdir
if [ $? -eq 0 ];then
echo "Successfull";
else
echo "Unsuccessfull";
fi
'
Upvotes: 4