仅将部分脚本作为sudo运行,仅输入一次密码

我正在编写一个安装外部依赖项的脚本(实际上是脚本和makefile的组合):一些apt-get命令,一些git克隆,构建,安装,将用户添加到组,…

这些脚本中的某些操作需要超级用户权限,有些则不需要。

到目前为止,我已经使用sudo运行整个make过程,但它有一些缺点:

  • git repos我克隆得到root作为所有者,这意味着我不能在没有sudochown情况下修改它们
  • 将用户添加到组的脚本不知道自whoami返回root以后要添加哪个用户

以超级用户身份运行只需要它的命令的最佳方法是什么? 理想情况下,该过程仍然需要我输入我的sudo密码,但在安装过程的最开始只需要输入一次。 它会在最后忘记它,但在此之前一直保持它(它可能需要几个小时)。

我在网上找到的解决方案包括:

  • sudo -v在脚本的begninning,但如果我理解正确这一次。 我的脚本可以运行几个小时
  • 使用sudo运行脚本,但是不需要超级用户使用sudo -u $(logname) 。 这就是我现在所做的,但感觉应该是另一种方式。

理想情况下,我希望我的脚本:

  1. 请求超级用户凭据
  2. 以登录用户身份运行普通命令
  3. 使用在步骤1中输入的凭据运行sudo命令
  4. sudo -k关闭超级用户会话

由于您具有sudo访问权限,因此请为自己创建一个sudoers文件,然后在脚本完成后将其删除:

 # grant this user access to the sudo commands without passwords # add all required cmds to the CMDS alias sudo tee /etc/sudoers.d/$USER < 

我一般不推荐的一种方法是自己读密码,并在需要时使用sudo-S选项传递密码:

 #! /bin/bash IFS= read -rsp 'Enter your password: ' password git clone ... sudo -S apt-get install foo -y <<<"$password" 

来自man sudo

  -S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.