1.1相关命令

编写脚本过程中主要使用两个命令useradd和passwd,可是使用man命令查看帮助。

man passwd
--stdin
This option is used to indicate that passwd should read the new password from standard input, which can be a pipe.
#可以使用标准输入的方式获取用户的新密码,且可以使用管道命令。
-e     
This is a quick way to expire a password for an account.  The  user  will  be  forced  to  change  the password during the next login attempt.Available to root only.
#用户下次登录时必须修改用户密码,且只有管理员能使用。

useradd  username
#管理员使用上面的命令就可以添加username用户。


1.2建立创建用户脚本

要求:创建user1到user5  5个用户,初始的用户密码和用户名相同。命令执行过程中不输出但需要提示用户创建成功,且创建的用户在登录时必须修改密码。

[root@vmoracle ~]# vi createuser.sh 
#!/bin/bash
for (( i=1 ; i<=5 ; i++ ))
{
        username=user${i}
        #用户名赋值到变量中
        useradd $username
        echo $username | passwd --stdin $username | >/dev/null
        #使用标准输入创建用户密码,执行过程的输出输出到/dev/null中
        passwd -e $username | >/dev/null
        #下次登录时必须修改密码
        echo "The user $username is created"
        #userdel -r $username
        #删除用户
}
#编辑完成后保存并退出

[root@vmoracle ~]# chmod u+x createuser.sh 
[root@vmoracle ~]# ./createuser.sh
#添加权限并执行  
The user user1 is created
The user user2 is created
The user user3 is created
The user user4 is created
The user user5 is created

1.3结果验证

[root@vmoracle ~]# tail -5 /etc/passwd
#查看/etc/passwd的末尾5行
user1:x:1002:1002::/home/user1:/bin/bash
user2:x:1003:1003::/home/user2:/bin/bash
user3:x:1004:1004::/home/user3:/bin/bash
user4:x:1005:1005::/home/user4:/bin/bash
user5:x:1006:1006::/home/user5:/bin/bash

[user1@vmoracle ~]$ su - user2
#切换到用户user2
Password: 
You are required to change your password immediately (root enforced)
Changing password for user2.
(current) UNIX password: 
#提示输入新密码