linux 要求用户从根模式运行makefile

oo7oh9g9  于 2023-01-12  发布在  Linux
关注(0)|答案(4)|浏览(142)

我有一个makefile和configure shell在我的项目中。我写了代码要求用户运行configure shell在根模式下使用以下代码。

[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"

但是当我运行“make install”时,我需要让用户从根模式运行。所以我只是从配置shell中复制代码,并将其复制到另一个名为“runasroot.sh”的shell脚本文件中。然后我从make install运行此shell脚本。

install:
    @echo About to install XXX Project
    ./runasroot.sh
    find . -name "*.cgi" -exec cp {}  $(SCRIPTDEST)/ \;

当我运行上面的代码时,我得到了下面的错误。

About to install XXX Project
./runasroot.sh \;
make: *** [install] Error 1

runasroot.sh

#!/bin/bash
[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"
vi4fp9gy

vi4fp9gy1#

target:
       @if ! [ "$(shell id -u)" = 0 ];then
             @echo "You are not root, run this target as root please"
             exit 1
       fi
z18hc3ub

z18hc3ub2#

解释

您可以使用ifneq检查用户是否为root用户,并回显一条消息,例如,如果用户确实是root用户,则不执行实际操作。由于root用户的ID在类UNIX操作系统上通常为0,因此我们可以在条件中检查用户ID是否为0

建议解决方案

install:
ifneq ($(shell id -u), 0)
    @echo "You must be root to perform this action."
else
    @echo "TODO: The action when the user is root here..."
endif

输出

$ make install
You must be root to perform this action.
$ sudo make install
TODO: The action when the user is root here...

外部资源

Makefile的条件部分
The shell Function
Recipe Echoing
Man for the id function
What is a root user

8yparm6h

8yparm6h3#

这里有几个错误。
第一个问题是你要做什么。在构建过程中要求root是非常糟糕的。对于构建部分,尝试不要求root来编译任何东西。如果你需要创建特殊的文件作为打包的一部分,使用fakerootfakeroot-ng来获得相同的效果,而不需要任何实际的权限提升。
对于安装,只要让用户以root用户身份运行整个make文件,如果她选择这样做的话。许多操作 * 通常 * 需要root用户,有时候不需要。例如,如果安装到用户有权限的DESTDIRmake install就不需要root用户。
然而,如果你执意要这样做,你的流程就完全错了。虽然runasroot.sh完全按照你的要求去做,但它只是为自己做。当你查看制作收据时:

install:
    @echo About to install XXX Project
    ./runasroot.sh # <<-- this line runs as root
    find . -name "*.cgi" -exec cp {}  $(SCRIPTDEST)/ \;

runasroot.sh行作为根运行,但find行是一个不同的进程,完全不受影响。
这对于常规shell脚本是正确的,但对于make receipt更是如此。在shell脚本中,每个命令都有自己的进程。在make receipt中,每个命令都有自己的***shell***。您的runasroot.sh不会也不能影响find运行时的权限。
所以,你正在尝试做的事情是不可能的,也是不需要的。如果你没有足够的权限,就尝试安装,失败。

v6ylcynt

v6ylcynt4#

如果用户不是root用户,则使用sudo和保留的所有参数再次自动调用make

install:
ifneq ($(shell id -u), 0)
    sudo make $@
else
    echo Your commands here...
endif

相关问题