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

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

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

有人能帮忙吗?


当前回答

使用stty关闭echo,然后再次打开。

其他回答

你也可以在不设置当前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)

使用stty关闭echo,然后再次打开。

一个衬套:

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

我发现askpass命令很有用

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

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

这里有另一种方法:

#!/bin/bash
# Read Password
echo -n Password: 
read -s password
echo
# Run Command
echo $password

read -s将为您关闭echo。只需将最后一行的echo替换为您想要运行的命令。

在一些shell(例如bash)中,read支持-p prompt-string,这将允许echo和read命令合并。

read -s -p "Password: " password