Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

c - how to execute a command as root

I develop a C code on Linux (Debian). Time to time, I need to execute some commands through system()

I wonder if it is possible to execute a command via system()as root. If it is not the case, is there any function to execute a command (or run a binary) as root that I can use on the C code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We met the situation before that we want to execute a root command by a normal user, here is our solution (using setuid/SUID):

assume that:

  • username: Tom
  • group: gTom
  • C program file: my_pro.c

Step 1: Write a C code tool: my_sudo.c

...
int main(int args, char *argv[]) {
    if (args < 2) 
        printf("Usage: my_sudo [cmd] [arg1 arg2 ...]");

    // cmd here is the shell cmd that you want execute in "my_pro"
    // you can check the shell cmd privilege here
    // example:  if (argv[1] != "yum") return; we just allow yum execute here

    char cmd[MAX_CMD];
    int i;
    for ( i = 2; i < args; i ++) {
    // concatenate the cmd, example: "yum install xxxxx"
        strcat(cmd, " ");
        strcat(cmd, argv[i]);
    }

    system(cmd);
} 

Step 2: Compile my_sudo.c to get a my_sudo executable file

   sudo chown root:gTom my_sudo   // user root && gTom group
   sudo chmod 4550 my_sudo        // use SUID to get root privilege

   #you will see my_sudo like this(ls -l)
   #-r-sr-x--- 1 root my_sudo 9028 Jul 19 10:09 my_sudo*

   #assume we put my_sudo to /usr/sbin/my_sudo

Step 3: In your C code

...
int main() {
    ...
    system("/usr/bin/mysudo yum install xxxxx");
    ...
}

#gcc && ls -l
#-rwxr--r--  1 Tom gTom 1895797 Jul 23 13:55 my_pro

Step 4: Execute./my_pro

You can execute the yum install without sudo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...