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

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

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

有人能帮忙吗?


当前回答

一个衬套:

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

其他回答

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

https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-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

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

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

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

使用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)