用bash中的命令行创建用户

时间:2013-12-01 11:57:56

标签: linux bash shell ubuntu

我想创建一个用户帐户,同时自定义命令行安装,以下代码几乎相当不错:

#!/bin/bash
#nameofuser stands for the new account
#skel is for the a skel folder outside /etc/skel     
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " nameofuser
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null

 if [ $? -eq 0 ]; then
 echo "$username exists!"
 exit 1

else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $nameofuser -c new created user -k $skel
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi

如果输入为空或不符合某些密码规范,我需要第二部分和reloop的帮助。

所以这是第二部分

我怎样才能确保if语句证明一些东西,比如最小密码lenth,以及密码是否至少包含特殊字符和数字或数字?

如果此检查不符合给定值,我如何强制用户重新键入密码?

2 个答案:

答案 0 :(得分:0)

使用类似的东西:

passwdok=0
while [ $passwdok == 0 ]  ; do
    read -s -p "Enter password : " password
    if [[ ! $password =~ ^.{6,} ]] ; then
        echo "Password should be at least 6 characters"
    elif [[ ! $password =~ [^A-Za-z0-9] ]] ; then
        echo "Password should contain a special character"
    else
        passwdok=1
    fi
done

答案 1 :(得分:0)

如果要强制使用强密码,请不要在这样的脚本中执行,而是使用Linux的身份验证系统,名为 PAM 可插入身份验证模块。特别是,启用 cracklib 模块。它涉及像/etc/pam.d/common-auth这样的编辑:

password required pam_cracklib.so retry=3 minlen=6 difok=3
password required pam_unix.so md5 use_authtok

这只是一个例子,你可能想要自定义它。编辑/etc/pam.d下的文件时要小心,如果您犯了错误,可以将自己锁定在系统之外。

Here's a nice write-up on the subjecthere's the official documentation of PAM

这样,您就可以有效地将密码强度验证移出脚本。无论如何,它应该是认证系统的责任,Linux让你很容易。

如果您对此有任何跟进问题,请尝试https://serverfault.com/