有时候我们维护一些服务需要用到root权限这个时候如果你是非Root该怎么办呢

以前公司的做法是给维护人员开普通用户,个别命令会调用一个钩子拿到root权限在去执行

代码寥寥无几

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
 
int main(int argc, char **argv)
{
        int i;
        int len;
        char *cmd = NULL, *prog = "";
        int ret;
 
    if (0 != setuid(0)) {
            printf("ERROR: can not setuid\n");
            exit(1);
    }
 
    len = strlen(prog);
    for (i=1; i<argc; i++) {
            len += 1 + strlen(argv[i]);
    }
 
    cmd = (char *) malloc(len+1);
    memset(cmd, 0, len+1);
    strcat(cmd, prog);
    for (i=1; i<argc; i++) {
            strcat(cmd, " ");
            strcat(cmd, argv[i]);
    }
 
    ret = system(cmd);
    return ret;
}

编译运行

1
2
3
4
# gcc exec.c -o exec
# chmod 4011 exec
# ./exec whoami
##result is root