关于shell脚本设置SUID的问题。

我写了个脚本quit.sh,如下:
  1 #/bin/bash
  2 if [ $# -lt 1 ];then
  3   echo"You must input at least one parameter!"
  4   exit 1
  5 fi
  6
  7 if [ $1 == "q" ];then
  8   echo "quit!"
  9   echo "$(whoami) quit @ $(date)">> /tmp/quit.txt      #这里访问了quit.txt
10   exit 0
11 else
12   echo "wrong input!"
13   exit 2
14 fi
   
    我将quit.txt的权限锁住,只有root可以读写,将quit.sh的用户和组都设置为root,并为其设置了SUID,希望其他用户可以通过该脚本读写quit.txt。但是执行起来却是Permission denied,请问这是为啥?
    执行过程如下:

[root@(none) tmp]# ll quit.txt
-rw-------. 1 root root 0 Jan 26 23:29 quit.txt
[root@(none) tmp]# ll quit.sh
-rwsr-xr-x. 1 root root 228 Jan 26 23:29 quit.sh
[root@(none) tmp]# ./quit.sh q                           ----->此处root执行正常
quit!
[root@(none) tmp]# cat quit.txt
root quit @ Tue Jan 26 23:31:15 PST 2016
[root@(none) tmp]# su - tom                             ------>切换到tom用户
[tom@(none) ~]$ cd /tmp/
[tom@(none) tmp]$ ./quit.sh q                          ------->这时候tom执行,进程的属主和属组应该是root,应该可以访问quit.txt才对,但是却提示没有权限
quit!
./quit.sh: line 9: /tmp/quit.txt: Permission denied

经多方查证,发现为shell脚本设置SUID是无效的:

尽管可以对 shell 脚本设置 suid 和 sgid 权限,但是大部分现代 shell 都会对脚本忽略这些位的设置。因为shell 是一种功能非常强大的脚本语言,拥有解释和执行任意表达式的能力。这些特性允许的限制太过宽泛,这就使环境变得非常不安全。因此,如果您对一个 shell 脚本设置了 suid 或 sgid 权限,就不要期望脚本在执行时能够遵守这些设置。

原文地址:https://www.cnblogs.com/hilnx/p/5166556.html