c - how to execute a command as root -
i develop c code on linux (debian). time time, need execute commands through system()
i wonder if possible execute command via system()
as root. if not case, there function execute command (or run binary) root can use on c code?
we met situation before want execute root command normal user, here our solution (using setuid/suid):
assume that:
- username:
tom
- group:
gtom
- c program file:
my_pro.c
step 1: write c code tool: my_sudo.c
... int main(int args, char *argv[]) { if (args < 2) printf("usage: my_sudo [cmd] [arg1 arg2 ...]"); // cmd here shell cmd want execute in "my_pro" // can check shell cmd privilege here // example: if (argv[1] != "yum") return; allow yum execute here char cmd[max_cmd]; int i; ( = 2; < args; ++) { // concatenate cmd, example: "yum install xxxxx" strcat(cmd, " "); strcat(cmd, argv[i]); } system(cmd); }
step 2: compile my_sudo.c
my_sudo
executable file
sudo chown root:gtom my_sudo // user root && gtom group sudo chmod 4550 my_sudo // use suid root privilege #you see my_sudo this(ls -l) #-r-sr-x--- 1 root my_sudo 9028 jul 19 10:09 my_sudo* #assume put my_sudo /usr/sbin/my_sudo
step 3: in 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 yum install
without sudo
.
Comments
Post a Comment