#!/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
}
[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
[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 ...
41
一个班轮:
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
7 回答
使用stty关闭
echo
,然后再打开 .这是另一种方法:
read -s
将为您关闭回声 . 只需将最后一行的echo
替换为您要运行的命令即可 .read
的-s
选项未在POSIX标准中定义 . 见http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html . 我想要一些适用于任何POSIX shell的东西,所以我写了一个小函数,使用stty
来禁用echo .此函数的行为与
read
命令非常相似 . 以下是read
的简单用法,后面跟read_secret
的类似用法 .read_secret
的输入显示为空,因为它未回显到终端 .这是另一个使用
-r
选项来保留输入中的反斜杠 . 这是有效的,因为上面定义的read_secret
函数将它接收的所有参数传递给read
命令 .最后,这是一个示例,演示如何使用
read_secret
函数以符合POSIX的方式读取密码 .一个班轮:
在Linux(和cygwin)下,这个表单适用于bash和sh . 但它可能不是标准的Unix sh .
有关更多信息和选项,请在bash中键入“help read” .
首先,如果有人要在文件中存储任何密码 . 我会确保它是哈希的 . 它不是最好的安全性,但至少它不会是纯文本 .
echo“password123”| md5sum | cut -d' - ' - f 1> / tmp / secret
#!/斌/庆典
我发现
askpass
命令很有用每个输入字符都替换为* . 请参阅:提供密码****