如何通过在 bash 脚本中输入两次来安全地确认密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22249029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:49:50  来源:igfitidea点击:

How to safely confirm a password by entering it twice in a bash script

bash

提问by Passuf

I would like to create a bash script where a user can choose a username, a password and confirm the password by entering it twice. If the passwords do not match the user should be prompted to enter it again. If the passwords match, the script should create a passwordhash, otherwise ask again until it is correct.

我想创建一个 bash 脚本,用户可以在其中选择用户名、密码并通过输入两次来确认密码。如果密码不匹配,则应提示用户再次输入。如果密码匹配,脚本应该创建一个密码哈希,否则再次询问直到正确。

So far I have the code below but I am not sure if this is the right way to do this. Is there a problem with the following bash script?

到目前为止,我有下面的代码,但我不确定这是否是正确的方法。下面的bash脚本有问题吗?

# read username
read -p "Username: " username

# read password twice
read -s -p "Password: " password
echo 
read -s -p "Password (again): " password2

# check if passwords match and if not ask again
while [ "$password" != "$password2" ];
do
    echo 
    echo "Please try again"
    read -s -p "Password: " password
    echo
    read -s -p "Password (again): " password2
done

# create passwordhash
passwordhash=`openssl passwd -1 $password`

# do something with the user and passwordhash

回答by Juan Diego Godoy Robles

A way to reduce verbosity:

一种减少冗长的方法:

#!/bin/bash

read -p "Username: " username
while true; do
    read -s -p "Password: " password
    echo
    read -s -p "Password (again): " password2
    echo
    [ "$password" = "$password2" ] && break
    echo "Please try again"
done