密码检查程序

密码检查程序

我为此绞尽脑汁了好一阵子。这个密码检查程序可以确保给定的密码包含:

  • 大写和小写字母
  • 至少 10 位数字
  • 至少一个数字

代码几乎可以正常工作,但大写字母除外。当插入单个大写字母作为密码时,程序会更改 flagncap 的值,而实际上不应该更改。有人能帮忙吗?

#!/bin/bash

echo "Please enter password: "
read user_passwd
flaglng=0
flagcap=0
flagncap=0
flagnum=0
if [[ ${#user_passwd} -ge 10 ]]; then
    flaglng=1
fi

if [[ "$user_passwd" = *[A-Z]* ]]; then
    flagcap=1
fi

if [[ "$user_passwd" = *[a-z]* ]]; then
    flagncap=1
fi

if [[ "$user_passwd" = *[0-9]* ]]; then
    flagnum=1
fi

if [[ "$flaglng" == 1 && "$flagcap" == 1 && "$flagncap" == 1 && "$flagnum" == 1 ]]; then
     echo "Password Strong!"
fi

if [[ "$flaglng" = 0 ]]; then
   echo "Weak Password! It should include at least 10 characters."
fi

if [[ "$flagcap" = 0 ]]; then
    echo "Weak Password! It should include at least 1 upper case letter."
fi

if [[ "$flagncap" = 0 ]]; then
    echo "Weak Password! It should include at least 1 lower case letter."
fi

if [[ "$flagnum" = 0 ]]; then
    echo "Weak Password! It should include at least 1 number."
fi

答案1

无论何时使用字符范围,最好在脚本开头插入export LC_ALL=C(或者如果您需要支持 ASCII 范围之外的字符),否则您可能会对其含义感到惊讶......C.UTF-8A-Za-z

例如:

$ unset LC_ALL
$ export LANG=en_US.UTF-8
$ [[ 'abc' = *[A-Z]* ]] && echo Match || echo No match
Match
$ export LC_ALL=C
$ [[ 'abc' = *[A-Z]* ]] && echo Match || echo No match
No match

shell 将范围[A-Z]视为当前语言环境中排序在 和 之间的所有字符。在 语言A环境中排序在 和 之间;因此匹配。另一方面,在语言环境中不在和之间排序,因为在语言环境中字符严格按照其代码点排序。Zen_USbAZabc*[A-Z]*CbAZC

答案2

首先,你需要不是不需要那么多分支if。完全不需要。相反,可以这样做:

goodpassword=1

...

if [[ "$user_passwd" = *[A-Z]* ]]; then 
    echo "Weak Password! It should include at least 1 upper case letter."
    goodpassword=0
fi

...

if [[ "$goodpassword" = 1 ]]; then
    echo "Good password!"
fi

要修复与 glob 相关的问题,请改用正则表达式。删除*并使用~

if [[ "$user_passwd" =~ [A-Z] ]]; then 
    flagcap=1
fi

正则表达式通常可以让你更好地控制匹配和验证。事实上,如果你愿意,你可以将整个脚本压缩为一个正则表达式(尽管这样会失去冗长性)。

样本:

$ ./pwcheck.sh 
Please enter password : 
a
Weak Password! It should include at least 10 characters.
Weak Password! It should include at least 1 upper case letter.
Weak Password! It should include at least 1 number.

$ ./pwcheck.sh 
Please enter password : 
A
Weak Password! It should include at least 10 characters.
Weak Password! It should include at least 1 lower case letter.
Weak Password! It should include at least 1 number.

相关内容