Hey*_*Hey 19 shell scripting password posix
当我想在bash
脚本中要求输入密码时,我会这样做:
read -s
Run Code Online (Sandbox Code Playgroud)
...但是当我bash
在 POSIX 模式下运行时sh
,该-s
选项被拒绝:
$ read -s
sh: 1: read: Illegal option -s
Run Code Online (Sandbox Code Playgroud)
如何使用符合 POSIX 的命令安全地请求输入?
Sté*_*las 25
read_password() {
REPLY="$(
# always read from the tty even when redirected:
exec < /dev/tty || exit # || exit only needed for bash
# save current tty settings:
tty_settings=$(stty -g) || exit
# schedule restore of the settings on exit of that subshell
# or on receiving SIGINT or SIGTERM:
trap 'stty "$tty_settings"' EXIT INT TERM
# disable terminal local echo
stty -echo || exit
# prompt on tty
printf "Password: " > /dev/tty
# read password as one line, record exit status
IFS= read -r password; ret=$?
# display a newline to visually acknowledge the entered password
echo > /dev/tty
# return the password for $REPLY
printf '%s\n' "$password"
exit "$ret"
)"
}
Run Code Online (Sandbox Code Playgroud)
请注意,对于那些printf
未内置的shell (mksh) ,密码将在ps
输出中以明文形式显示(几微秒),或者如果所有带有参数的命令调用都被审计,则密码可能会显示在某些审计日志中。
ser*_*sat 23
read -s
不在 POSIX 中。如果您想符合 POSIX 标准,请使用stty -echo
. stty
其echo
参数在 POSIX 中定义。
#!/bin/bash
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"
Run Code Online (Sandbox Code Playgroud)
这将适用于所有符合 POSIX 的 shell。