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

Execute commands as root without root password or sudo

我理解 运行将脚本作为 root 的含义,尤其是通过 Web 应用程序。但是,作为我的 Web 应用程序的一部分,我需要将 curl 与 tor 一起使用,这需要偶尔重置 tor ip。使用 service tor restart 重新启动服务后,tor 可以获得新的 ip。由于只有 root 可以执行此操作,因此我编写了一个 C 包装器脚本来执行我需要的操作,编译它并在其上设置 setuid root,并更改为 root 用户所有权。但是,当它作为非特权用户 运行 时,它仍然会询问我 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 }' | 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