I have a script that executes three functions: A && B && C
.
Function B
needs to be run as a super-user, while A
and C
don't.
I have several solutions but neither of these are satisfying:
sudo the entire script: sudo 'A && B && C'
That seems like a bad idea to run A
and C
as super-user if it's not
needed
make the script interactive: A && sudo B && C
I might have to type-in my password, but I want my script to be non-interactive, as each function can take some time, and I don't want the script to wait for me. Well, that's also why it's a script in the first place, so I don't have to watch it run.
The stupid solution: sudo : && A && sudo -n B && C
首先,首先运行无操作似乎很愚蠢sudo
,而且我必须交叉手指,A 不会超过$sudo_timeout
.
假设解决方案(我希望你告诉我它存在):
sudo --store-cred 'A && sudo --use-cred-from-parent-sudo B && C'
这会在开始时提示我输入密码,然后仅在需要时使用该凭据。
你对这一切有什么看法?我会很惊讶这个问题没有解决方案,因为我认为这是一个非常普遍的问题(怎么样make all && sudo make install
)
将您的脚本添加到/etc/sudoers
具有该NOPASSWD
属性的文件中,以便允许它在不提示输入密码的情况下运行。您可以将其绑定到特定用户(或一组用户),或允许sudo
系统上的任何人运行它。
称为脚本的示例行/usr/local/bin/bossy
可能如下所示
ALL ALL = (root) NOPASSWD: /usr/local/bin/bossy
Run Code Online (Sandbox Code Playgroud)
然后你会使用这样的东西
A && sudo bossy && C
Run Code Online (Sandbox Code Playgroud)
对于这个例子,我假设PATH
包括/usr/local/bin
. 如果没有,那么只需使用脚本的完整路径,即sudo /usr/local/bin/bossy
我认为你能做的最好的事情是启动脚本,sudo
然后启动你想作为普通用户显式运行的进程su user
或sudo -u user
:
#!/usr/bin/env bash
## Detect the user who launched the script
usr=$(env | grep SUDO_USER | cut -d= -f 2)
## Exit if the script was not launched by root or through sudo
if [ -z $usr ] && [ $UID -ne 0 ]
then
echo "The script needs to run as root" && exit 1
fi
## Run the job(s) that don't need root
sudo -u $usr commandA
## Run the job that needs to be run as root
commandB
Run Code Online (Sandbox Code Playgroud)