如何让“sudo”从文件中获取密码?

Mic*_*elB 15 sudo 12.04

我想运行一个需要 sudo 密码的命令说:

sudo apt-get update
Run Code Online (Sandbox Code Playgroud)

这不是应该工作吗(我已将密码存储在普通文本文件中passwd.txt):

sudo apt-get update <~/passwd.txt
Run Code Online (Sandbox Code Playgroud)

这是我为什么它应该工作的逻辑:当需要密码时,要求用户从键盘输入密码。但是重定向stdin到从passwd.txt文件中读取应该可以工作。

不应该吗?

Eri*_*lho 30

sudostdin默认情况下不读取密码。从sudo联机帮助页:

-S  The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
    The password must be followed by a newline character.
Run Code Online (Sandbox Code Playgroud)

所以你应该运行:

sudo -S apt-get update <~/passwd.txt
Run Code Online (Sandbox Code Playgroud)

请记住,将密码存储在文件中不是一个好习惯。你应该阅读:

  • 为了使其自我记录,我只需使用“sudo --stdin apt-get update” (2认同)