首页 > 解决方案 > 如何以 root 和非交互方式运行 exec() 函数?

问题描述

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

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

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

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

标签: cpermissionsexecrootdaemon

解决方案


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

“似乎一旦调用 exec 函数,权限就不会从主线程传递。”

我写了以下测试代码,

#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 权限的子进程创建了一个目录。


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

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

你真正想要的是一个无密码的 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

推荐阅读