设计一个Shell脚本程序,实现一个简单的密码生成器功能,用户输入密码长度和复杂度要求后,生成符合要求的随机密码。
编写Shell脚本生成密码
下面是一个示例Shell脚本程序,用于生成符合要求的随机密码。用户可以输入密码长度和复杂度要求,程序将输出符合要求的随机密码。
#!/bin/bash
# 生成随机密码的函数
generate_password() {
# 从/dev/urandom读取随机字符,使用tr进行字符映射,然后使用head命令选择指定长度的字符
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c $1
}
# 输入密码长度
read -p '请输入密码长度:' length
# 输入密码复杂度要求
read -p '请输入密码复杂度要求(low/medium/high):' complexity
# 根据复杂度要求确定密码字符范围
if [ $complexity == 'low' ]; then
characters='a-zA-Z0-9'
elif [ $complexity == 'medium' ]; then
characters='a-zA-Z0-9@#$%'
else
characters='a-zA-Z0-9@#$%&*()'
fi
# 生成密码
password=$(generate_password $length | tr -dc $characters)
# 输出密码
echo "生成的密码为: $password"
示例
用户输入密码长度:8 用户输入密码复杂度要求:medium
生成的密码为: n7T#0@6@