我有一个脚本,自动需要访问密码保护系统的进程。通过一个接受用户密码作为参数的命令行程序访问系统。

我想提示用户输入密码,将其分配给一个shell变量,然后使用该变量构造访问程序的命令行(当然,这将产生我将处理的流输出)。

我在Bourne/Bash中是一个相当称职的shell程序员,但我不知道如何接受用户输入而不让它回显到终端(或者可能让它使用'*'字符回显)。

有人能帮忙吗?


当前回答

这个链接有助于定义, *如何从使用中读取密码而不将其返回到终端 *如何用* -character替换每个字符。

https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-password/

其他回答

一个衬套:

read -s -p "Password: " password

在Linux(和cygwin)下,这种形式在bash和sh中工作。不过,它可能不是标准的Unix sh。

更多信息和选项,在bash中输入“help read”。

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
  ...
  -p prompt output the string PROMPT without a trailing newline before
            attempting to read
  ...
  -s                do not echo input coming from a terminal

一个POSIX兼容的答案。注意使用/bin/sh而不是/bin/bash(它可以使用bash,但不需要bash。)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

我发现askpass命令很有用

password=$(/lib/cryptsetup/askpass "Give a password")

每个输入字符都替换为*。看到的: 给出密码****

虽然已经有很多答案,但在几乎所有运行systemd的现代linux中,还有一种方法可以从终端询问密码(是的,我知道,但你能做些什么呢)。systemd-ask-password命令包含在标准的核心systemd包中,可以像这样使用:

#!/bin/sh
PASSWORD="$(systemd-ask-password "Enter your password:")"

使用——emoji=no开关来抑制愚蠢的unicode锁定字符。它在终端内工作得很好,但如果你需要它弹出一个GUI对话框,则需要调整,但这超出了这里的范围。

你也可以在不设置当前shell变量的情况下提示输入密码,如下所示:

$(read -s;echo $REPLY)

例如:

my-command --set password=$(read -sp "Password: ";echo $REPLY)

你可以用换行符添加这些提示值,这样做:

my-command --set user=$(read -sp "`echo $'\n '`User: ";echo $REPLY) --set password=$(read -sp "`echo $'\n '`Password: ";echo $REPLY)