如何执行命令根
问题描述:
我开发在Linux(Debian的)一个C code。每隔一段时间,我需要通过来执行某些命令系统()
I develop a C code on Linux (Debian). Time to time, I need to execute some commands through system()
我不知道是否有可能通过来执行命令系统()
为根。如果不是这种情况,是因为有根,我可以在C code?
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?
答
步骤2:编译
Step 2: Compile
步骤4:执行
我们遇到了,以前我们想通过普通用户执行root命令的情况下,这里是我们的解决方案(使用的setuid / SUID):
We met the situation before that we want to execute a root command by a normal user, here is our solution (using setuid/SUID):
假设:
- 用户名:
汤姆
- 组:
gTom
- C程序文件:
my_pro.c
-
username:
Tom
-
group:
gTom
-
C program file:
my_pro.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);
}
步骤2:编译 my_sudo.c
获得 my_sudo
可执行文件
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
步骤3:在你的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
步骤4:执行 ./ my_pro
您可以执行百胜安装
没有须藤
。