歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux 中判斷指定用戶對指定目錄的訪問權限

Linux 中判斷指定用戶對指定目錄的訪問權限

日期:2017/2/28 14:55:58   编辑:Linux教程

腳本名:power.sh

腳本內容

  1. #!/bin/sh
  2. username3=$1
  3. file_path=$2
  4. if [ `id -u` -ne 0 ]; then
  5. echo "Please re-run `basename $0` as root."
  6. exit 1
  7. fi
  8. # Get existing directory
  9. while true
  10. do
  11. if [ -d $file_path ];then
  12. break;
  13. fi
  14. file_path=${file_path%/*}
  15. done
  16. dir_name2=$file_path
  17. # Judge whether the user exists
  18. grep "^$username3:" /etc/passwd >/dev/null
  19. if [ $? -ne 0 ];then
  20. echo "This user \"$username3\" does not exist."
  21. exit 4
  22. fi
  23. su -l $username3 -c "test -r $dir_name2"
  24. is_read=$?
  25. su -l $username3 -c "test -x $dir_name2"
  26. is_exe=$?
  27. su -l $username3 -c "test -w $dir_name2"
  28. is_write=$?
  29. is_read_int=0
  30. is_exe_int=0
  31. is_write_int=0
  32. if [ $is_read -eq 0 ];then
  33. is_read_int=100
  34. fi
  35. if [ $is_exe -eq 0 ];then
  36. is_exe_int=1
  37. fi
  38. if [ $is_write -eq 0 ];then
  39. is_write_int=10
  40. fi
  41. $result_and
  42. type let > /dev/null 2>&1
  43. if [ $? -eq 0 ];then
  44. let result_and=is_read_int+is_exe_int
  45. let result_and=result_and+is_write_int
  46. else
  47. result_and=`expr $is_read_int + $is_exe_int`
  48. result_and=`expr $result_and + $is_write_int`
  49. fi
  50. exit $result_and

應用:

sh power.sh user1 /opt/abc

若返回值為111,則表示用戶user1 對目錄 /opt/abc具有讀寫執行權限;

若返回值為101,則表示用戶user1 對目錄 /opt/abc具有讀執行權限;

若返回值為10,則表示用戶user1 對目錄 /opt/abc具有寫權限;

注意:必須以 root 執行 power.sh

Copyright © Linux教程網 All Rights Reserved