c - 如何以 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 身份运行进程的非交互式方式。除了删除守护进程的密码之外,还有什么方法可以做到这一点?
解决方案
为了测试你的问题的前提,
“似乎一旦调用 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
推荐阅读
- javascript - 我想使用 expo AsyncStorage 将商店持久化到 redux 但我收到错误
- javascript - 在Javascript中将行附加到现有的gridview而不循环
- azure - ASP.NET Core Web 应用程序作为 Azure 服务总线使用者/接收器
- ipad - iPad 模拟器不会在 Xcode 11 beta 5 中启动 NavigationView 应用程序吗?
- java - 使用重新抛出异常的异常处理程序有什么明显的区别吗
- php - 从给定日期获取一周前 PHP
- java - 从 Android 应用程序上传大型 PDF 文件时得到空白响应
- python - 如何将字符串中的以下时间戳(包含UTC时间)转换为python2.6中的纪元时间?
- python - 如何根据 python 中的位置将 1 列数据帧转换为 3
- django - 使用具有外键的模型序列化程序在 Django Rest Framework 中的父表上执行 CRUD