以 root 身份檢測指定用戶對指定目錄的實際讀/寫/執行權限,支援不存在目錄時向上遞迴查找最近存在的父目錄。
#!/bin/sh
# 檔名:check_user_dir_perm.sh
# 用法:sh check_user_dir_perm.sh <用戶名> <目標目錄>
username=$1
target_dir=$2
# 1. 向上遞迴找到存在的目錄
file_path=$target_dir
while true; do
if [ -d "$file_path" ]; then
break
fi
file_path=${file_path%/*}
# 防止遞迴到根目錄仍不存在
if [ "$file_path" = "" ]; then
file_path="/"
break
fi
done
target_dir=$file_path
# 2. 驗證用戶存在
if ! grep -q "^$username:" /etc/passwd; then
echo "This user \"$username\" does not exist."
exit 4
fi
# 3. 取得用戶主要群組
group=$(grep "^$username:" /etc/passwd | awk -F: '{print $4}' | xargs -i grep {} /etc/group | cut -d: -f1)
# 4. 以目標用戶身份測試權限(核心技巧)
su -l "$username" -c "test -r \"$target_dir\""
is_read=$?
su -l "$username" -c "test -x \"$target_dir\""
is_exe=$?
su -l "$username" -c "test -w \"$target_dir\""
is_write=$?
# 5. 格式化輸出 rwx 字串
read_char="-"
write_char="-"
exe_char="-"
[ $is_read -eq 0 ] && read_char="r"
[ $is_write -eq 0 ] && write_char="w"
[ $is_exe -eq 0 ] && exe_char="x"
echo "${read_char}${write_char}${exe_char}"
使用 su -l user -c "test -r path" 在目標用戶完整登入環境下測試權限,自動處理:
這比單純解析 ls -l 權限位準確得多。
${file_path%/*} # Shell 參數擴展:移除最後一個 / 及其後內容(取得父目錄)
[root@ppc40 study]# sh power.sh whuanga4 /tmp/abc/dd
This user "whuanga4" does not exist.
[root@ppc40 study]# sh power.sh whuang4 /tmp/abc/dd
rw-
# 表示:讀、寫權限有,執行權限無
test -O 檢查擁有者權限getfacl 顯示詳細 ACL