问题:
用非root 用户执行shell 脚本,但是有些操作好需要root 权限。哪怕给脚本加s属性也不起作用。
解决方案:
s属性只是对二进制程序起作用,因此加一个wrapper函数去调用脚本。
程序如下:
root_permision.c
1 #include <unistd.h>
2 #include <time.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5
7 {
8 if (argc < 2 )
9 {
10 fprintf(stderr,"Error:%s <script name>\n",argv[0]);
11 return 1;
12 }
13
14 char *tool = argv[1];
15 pid_t pid = fork();
16 int ret;
17 if (pid == 0)
18 {
19 setuid(0); // change to root user
20 if (execlp(tool,tool,NULL) < 0)
21 {
22 fprintf(stderr,"fail to run cmd\n");
23 exit(-1);
24 }
25 exit(0);
26 }
27 while (pid != waitpid(pid,NULL,0))
28 {
29 sleep(1);
30 }
31
32 return 0;
33 }
gcc -o run_by_root root_permision.c
switch to user root and run the following command
chown root:root run_by_root
chmod 5755 run_by_root
[ainet@localhost c++]$ ls -l run_by_root
-rwsr-xr-t. 1 root root 7331 Nov 12 20:22 run_by_root
create the test script cmd.sh
id
cd /root
pwd
[ainet@localhost c++]$ id
uid=500(ainet) gid=500(ainet) groups=500(ainet) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[ainet@localhost c++]$ ./run_by_root ./cmd.sh
uid=0(root) gid=500(ainet) groups=0(root),500(ainet) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
/root
脚本成功获取root权限并执行相关命令。