【发布时间】:2020-01-27 19:42:48
【问题描述】:
是否可以制作一个只以用户身份运行而不使用root权限的关机脚本?
我找到了这段代码,但它似乎什么也没做:
#include <unistd.h>
#include <sys/reboot.h>
int main () {
sync(); // If reboot() not preceded by a sync(), data will be lost.
setuid(0); // set uid to root, the running uid must already have the
// appropriate permissions to do this.
reboot(RB_AUTOBOOT); // note, this reboots the system, it's not as
return(0); // graceful as asking the init system to reboot.
}
系统信息:
Linux hosek 4.15.0-48-generic #51-Ubuntu SMP Wed Apr 3 08:28:49 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
【问题讨论】:
-
可以,但程序必须标记为 setuid root。只有 root 可以做到这一点。但是在 root 执行一次之后,它就会保持这种状态。
-
您忽略了来自
setuid()的返回值-它将返回-1,将errno设置为EPERM,如果您没有足够的权限,则保持uid 不变。你真的想要if (setuid(0) != 0) { perror(""); return 1; } -
@Omnifarious 所以不可能例如制作这个
c程序,上传到另一台服务器并运行这个命令来重启/关闭服务器? -
@genderbee 这是你的意图吗?
-
@genderbee - 这样看,您是否希望您刚刚在您的服务器上授予登录权限的人能够将其关闭?答案是否定的,而且应该是否定的。 Unix 系统上的随机人员无权关闭系统。如果您想在未经其他人(或公司)同意的情况下关闭其他随机人(或公司)的系统,那么您是在问我们如何做在大多数司法管辖区实际上是非法的事情。