测试一个给定用户是否可以读取一个目录及其内部所有文件的Bash脚本?

7
我需要在bash脚本中测试一个给定的用户是否可以读取给定目录中的所有文件和子目录。该脚本以root身份运行。
假设给定的用户名为$user,要测试的目录为$dir,我将以下行添加到脚本中:
su -m $user -c "test -r $dir && test -x $dir"
if [ $? -ne ]; then
   echo "$dir不可读或不可执行"
fi
你觉得这个翻译正确吗?
2个回答

4
  1. There seems to be something missing here:

    if [ $? -ne ]; then
    

    Surely you meant to write:

    if [ $? -ne 0 ]; then
    

    But in fact the test is not necessary because you can use ||:

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

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

    you can use the -a option (logical and) to test:

    test -r $dir -a -x $dir
    
  3. Where does the variable $user come from? Is it trusted? If not, there'll be trouble if someone supplies a value like root;. Even if you are sure that $user is OK in this case, it's still worth getting into the habit of quoting your variables in shell scripts: here you'd be safe if you had written:

    su -m "$user" -c "..."
    
  4. There's a similar problem if $dir is untrusted — someone might supply a value like /; sh. But in this case quoting it like this won't work:

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

    because someone might supply a value like /'; sh; echo '. Instead, you need to pass the quoted "$dir" to the subshell as a parameter which you can then refer to safely using $1:

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

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
看起来“find”即使有些文件不可读,也会返回0。我该如何测试$user可以读取$dir内的所有文件? - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接