非root 用户swith to root运行脚本

问题: 

用非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

     6  int main(int argc, char *argv[])
     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权限并执行相关命令。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值