2

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.

4

1 回答 1

4

两个问题:

1.) 你告诉过:

sudo -u testuser -H ...

什么意思:以 . 身份运行命令testuser,他无权写入,/usr/local因此您得到permission denied.

当您删除 时-u testuser,该命令将以 root 身份(默认)运行(没有密码testuser)并将创建目录。

似乎,您只是误解了sudoand的/etc/sudoers工作原理。-u user平均值_

-u user' -u (user) 选项使 sudo 以 root 以外的用户身份运行指定的命令。要指定 uid 而不是用户名,#uid。当以 uid 运行命令时,许多 shell 要求使用反斜杠 ('\') 对“#”进行转义。安全策略可能会将 uid 限制为密码数据库中列出的那些。只要未设置 targetpw 选项,sudoers 策略就允许密码数据库中没有的 uid。其他安全策略可能不支持这一点。

2.)第二个问题的Successfull消息。

正在sh -c. 这Variable expansion是在甚至开始之前完成的。sh -c所以使用单引号,会得到正确的Unsuccessfull信息:

sudo -u testuser -H sh -c '
mkdir /usr/local/testdir
if [ $? -eq 0 ];then
    echo "Successfull";
else
    echo "Unsuccessfull";
fi
'

并使用下一个作为解决方案:

sudo -H sh -c '
mkdir /usr/local/testdir
if [ $? -eq 0 ];then
    echo "Successfull";
else
    echo "Unsuccessfull";
fi
'
于 2013-07-29T09:43:12.473 回答