zl程序教程

您现在的位置是:首页 >  其他

当前栏目

bash练习11(创建一个用户并且设置密码)

密码密码 一个 设置 创建 用户 11 练习
2023-09-27 14:26:51 时间
#!/usr/bin/bash
# 创建一个用户,并且配置密码
# 用法:create_user username passwd
if [ $# -ne 2 ]
then
        echo "Usage:create_user username passwd"
        exit 1
fi

uid=$(id -u)
if [ $uid -ne 0 ]
then
        echo "You are not root, cannot create user"
        exit 1
fi

username=$1
password=$2

id ${username} &>/dev/null
if [ $? -eq 0 ]
then
        echo "${username} already exists,change the username and try again"
        exit 1
fi

useradd ${username} &>/dev/null
if [ $? -ne 0 ]
then
        echo "create ${username} failed"
        exit 1
fi

echo "${password}" | passwd --stdin ${username}
if [ $? -ne 0 ]
then
        echo "create ${username} failed"
        exit 1
fi

echo "create the ${username} with ${password} sucessfully!"

执行结果:

[root@gyl-huawei bash]# chmod +x adduser.sh     # 添加脚本执行权限
[root@gyl-huawei bash]# ./adduser.sh testuser abc123  # 测试脚本
Changing password for user testuser.
passwd: all authentication tokens updated successfully.
create the testuser with abc123 sucessfully!
[root@gyl-huawei bash]# su testuser  # 切换到新添加的用户
[testuser@gyl-huawei bash]$