gpt4 book ai didi

c - 如何以 root 身份以非交互方式运行 exec() 函数?

转载 作者:行者123 更新时间:2023-11-30 14:41:21 25 4
gpt4 key购买 nike

我正在寻找fork()并以root权限执行。似乎一旦调用 exec 函数,权限就不会从主线程传递。

现在我看到了帖子here描述了如何以 root 身份运行进程,但是当我尝试他们的解决方案时..

char sudo[]="/usr/bin/sudo";
char pbin[]="/usr/local/bin/puppet";
execl(sudo,sudo,pbin,(char *)NULL);

sudo 命令提示输入守护程序的密码。我正在寻找非交互式方式以 root 身份运行该进程。除了删除 Daemon 的密码之外,还有什么办法可以做到这一点吗?

最佳答案

为了测试你的问题的前提,

"It seems that privileges are not passed from the main thread once an exec function is called."

我编写了以下测试代码,

#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main() {
// printf("starting");
char sudo[]="/usr/bin/sudo";
char pbin[]="mkdir";

// printf("running test: %s %s",sudo,pbin);
errno=0;

if (fork() == 0) {
int res = execl(sudo,sudo,pbin,"/bin/child",(char *)NULL);
// printf("res:%d", res);
}
else {
sleep(2);
int res = execl(sudo,sudo,pbin,"/bin/parent",(char *)NULL);
// printf("res:%d", res);
}
}

令我惊讶的是,它毫无问题地运行,并给出以下输出:

$ sudo rm /bin/parent -rf ; sudo rm -rf /bin/child/
$ ls /bin/child/ -la
ls: cannot access '/bin/child/': No such file or directory
$ ls /bin/parent/ -la
ls: cannot access '/bin/parent/': No such file or directory

$ gcc main.c
$ sudo ./a.out

$ ls /bin/parent -la
total 8 drwxr-xr-x 2 root root 4096 Mar 6 11:42 .
drwxr-xr-x 4 root root 4096 Mar 6 11:42 ..
$ ls /bin/child -la
total 8 drwxr-xr-x 2 root root 4096 Mar 6 11:42 .
drwxr-xr-x 4 root root 4096 Mar 6 11:42 ..

正如您所看到的,有一个由父进程以及具有 root 权限的子进程创建的目录。

<小时/>

这让我认为您的问题实际上是其他问题,正如您所说:

"The sudo command prompts for daemon's password. I am looking for non-interactive way to run the process as root. Is there anyway to do this short of removing Daemon's password?"

你真正想要的是一个无密码的sudo,可以通过运行来获得

sudo visudo

然后添加行:

ALL     ALL=(ALL) NOPASSWD: ALL

使您的 sudoers 文件看起来像这样。

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL

ALL ALL=(ALL) NOPASSWD: ALL
# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

关于c - 如何以 root 身份以非交互方式运行 exec() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com