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

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

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

有人能帮忙吗?


当前回答

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

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

其他回答

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

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

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

我发现askpass命令很有用

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

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

read的-s选项在POSIX标准中没有定义。见http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html。我想要一些可以工作于任何POSIX shell的东西,所以我写了一个小函数,使用stty禁用echo。

#!/bin/sh

# Read secret string
read_secret()
{
    # Disable echo.
    stty -echo

    # Set up trap to ensure echo is enabled before exiting if the script
    # is terminated while echo is disabled.
    trap 'stty echo' EXIT

    # Read secret.
    read "$@"

    # Enable echo.
    stty echo
    trap - EXIT

    # Print a newline because the newline entered by the user after
    # entering the passcode is not echoed. This ensures that the
    # next line of output begins at a new line.
    echo
}

这个函数的行为与read命令非常相似。下面是read的简单用法,然后是类似的read_secret用法。read_secret的输入显示为空,因为它没有回显到终端。

[susam@cube ~]$ read a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c

下面是另一个使用-r选项来保留输入中的反斜杠。这是因为上面定义的read_secret函数将它接收到的所有参数传递给read命令。

[susam@cube ~]$ read -r a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret -r a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c

最后,下面是一个示例,演示如何使用read_secret函数以符合POSIX的方式读取密码。

printf "Password: "
read_secret password
# Do something with $password here ...