C语言 以 root 身份执行命令,无需 root 密码或 sudo



我理解以root身份运行脚本的含义,尤其是通过Web应用程序。但是,作为我的 Web 应用程序的一部分,我需要将 curl 与 tor 一起使用,这需要偶尔重置 tor ip。Tor 可以在使用service tor restart重新启动服务时获得新的 IP。由于只有 root 可以做到这一点,我编写了一个 C 包装器脚本来完成我需要的事情,并对其进行编译并在其上设置 setuid 根,并更改为 root 用户所有权。但是,当它以非特权用户身份运行时,它仍然会询问我的 root 密码。作为根用户,服务重启不应询问密码。

我的脚本:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void ExecAsRoot (char* str);
int main ()
{
setuid (0);
setvbuf(stdout, NULL, _IONBF, 0);
printf ("Host real ip is: ");
ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
ExecAsRoot("/usr/sbin/service tor restart");
// sleep(2);
printf ("Tor should have switched to a new ip by now.nNew ip is: ");
ExecAsRoot("torify curl ifconfig.co 2>/dev/null");
return 0;
}
void ExecAsRoot (char* str) {
system (str);
}

我做了以下工作:

chown root restartor
chmod u=rwx,go=xr restartor 

输出:

Host real ip is: 7.17.11.23
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to restart 'tor.service'.
Authenticating as: root
Password:

如何在不提供 root 密码的情况下让它以 Web 用户身份运行?

您没有在文件权限中设置 setuid 位:

#-------v
chmod u=srwx,go=xr restartor

最新更新