`sudo` 附加到具有 root 权限的文件(在 C 中的 `system(3)` 中) [英] `sudo` to append to file with root permissions (inside `system(3)` from C)
问题描述
我正在尝试使用 sudo
写入 /etc
中的文件,该文件只能由 root
从非特权 C 内部写入程序.
I am attempting to use sudo
to write to a file in /etc
that is writable only by root
, from inside an unprivileged C program.
system("sudo /bin/sh -c 'echo 'iface wlan0 inet dhcp' >> /etc/network/interfaces'");
这似乎没有失败,但文件未修改.怎么了?
This doesn't appear to fail, but the file is unmodified. What is wrong?
推荐答案
按照您所拥有的结构,重定向在 sudo
操作之外进行评估,因此不会有root权限,不能打开/etc/network/interfaces
进行写入.你需要这样做:
Structured as you have it, the redirection is evaluated outside the sudo
operation, and therefore does not have root privileges and cannot open /etc/network/interfaces
for writing. You need to do it like this instead:
system("sudo /bin/sh -c \"echo 'iface wlan0 inet dhcp' >> /etc/network/interfaces\"");
这样重定向就由 shell inside sudo 来评估.
so that the redirection is evaluated by the shell inside the sudo.
(另外,单引号内不能嵌套单引号.)
(Also, you can't nest single quotes inside single quotes.)
这篇关于`sudo` 附加到具有 root 权限的文件(在 C 中的 `system(3)` 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!