Bash脚本测试给定用户是否可以读取目录和所有文件?

时间:2013-10-24 14:52:52

标签: bash filesystems su

如果给定用户可以读取包含所有文件和子目录的给定目录,我需要在bash脚本中进行测试。该脚本以 root 运行。

假设给定的用户名为$user且要测试的目录为$dir,我将以下行添加到脚本中

su -m $user -c "test -r $dir && test -x $dir"
if [ $? -ne ]; then
   echo "$dir is not readable or executable"
fi

你会建议改正吗?

2 个答案:

答案 0 :(得分:4)

你可以简单地说:

su -m $user -c "find $dir >/dev/null 2>&1 || echo $dir is not readable or executable"

如果$dir中的任何文件/目录无法读取,则会生成不可读或可执行的消息。

如果

find $dir无法读取任何文件,则会返回非零的错误代码。


编辑:找到所有不可读的目录/文件的更完整(或可靠)的方式是:

find . \( -type d -perm /u+r -o -type d -perm /u+x -o -type f -perm /u+r \)

答案 1 :(得分:4)

  1. 这里似乎缺少一些东西:

    if [ $? -ne ]; then
    

    当然你打算写:

    if [ $? -ne 0 ]; then
    

    但实际上测试不是必需的,因为您可以使用||

    su -m $user -c "test -r $dir && test -x $dir" ||
    echo "$dir is not readable or executable"
    
  2. 而不是:

    test -r $dir && test -x $dir
    

    您可以使用-a选项(逻辑和)test

    test -r $dir -a -x $dir
    
  3. 变量$user来自何处?它值得信赖吗?如果没有,如果有人提供root;之类的值,就会出现问题。即使你确定$user在这种情况下是正常的,但仍然有必要养成在shell脚本中引用变量的习惯:如果你写完了,那么你将是安全的:

    su -m "$user" -c "..."
    
  4. 如果$dir不受信任,则存在类似问题 - 有人可能会提供类似/; sh的值。但在这种情况下引用它是不行的:

    su -m "$user" -c "test -r '$dir' -a -x '$dir'"
    

    因为有人可能会提供类似/'; sh; echo '的值。相反,您需要将引用的"$dir"作为参数传递给子shell,然后您可以使用$1安全地引用它:

    su -m "$user" -c 'test -r "$1" -a -x "$1"' -- "$dir"