萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 判斷指定用戶對目錄權限的 Shell 腳本實作

腳本功能

以 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 執行 test 指令

使用 su -l user -c "test -r path" 在目標用戶完整登入環境下測試權限,自動處理:

  • ACL 擴充屬性
  • 群組成員資格(含輔助群組)
  • 檔案系統掛載選項(noexec 等)
  • SELinux/AppArmor 安全上下文

這比單純解析 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 檢查擁有者權限
  • 支援多目錄批次檢查
  • 輸出 JSON 格式便於程式解析
  • 整合 getfacl 顯示詳細 ACL

注意事項

  • 必須以 root 執行(su 切換用戶需要權限)
  • 目標用戶需有有效 shell(/etc/passwd 最後欄位非 /sbin/nologin)
  • 網路檔案系統(NFS/SMB)權限取決於伺服器端設定
copyright © 萬盛學電腦網 all rights reserved