shell脚本一天一练----创建用户
#!/bin/bash
# *************************************
# * 功能: Shell脚本模板
# * 作者: 刘丹玉
# * 联系: v649352141@163.com
# * 版本: 2025-04-30
# *************************************
# 练习题
# 需求
# 创建10个用户,并给他们设置随机密码,密码记录到一个文件里,文件名为userinfo.txt
# 用户从user_00 到 user_09
# 密码要求:包含大小写字母以及数字,密码长度为15位
# 先查看/tmp/userinfo.txt文件是否存在,存在的话先删除,以免影响到本次脚本执行结果
if [ -f /tmp/userinfo.txt ]
then
rm -f /tmp/userinfo.txt
fi
# 借助seq生成从00到09、10个数的队列
for i in $(seq -w 0 09)
do
p=$(openssl rand -base64 15 | tr -dc 'a-zA-Z0-9' | head -c 15)
# 添加用户,并给该用户设置密码
useradd user_${i} && echo "${p}" | passwd --stdin user_${i}
echo "user_${i} ${p}" >> /tmp/userinfo.txt
done
### 关键知识点总结:
### 1) openssl rand -base64 15:生成 15 字节的随机数据,并以 Base64 编码输出。
### tr -dc 'a-zA-Z0-9':过滤输出,只保留大小写字母和数字。
### head -c 15:截取前 15 个字符。
### 2) seq可以生成序列,用法: seq 1 5; seq 5; seq 1 2 10; seq 10 -2 1;seq -w 1 10;
###
### 3) passwd --stdin username
[root@Rocky9-12 ~]#bash 0430-01.sh
Changing password for user user_00.
passwd: all authentication tokens updated successfully.
Changing password for user user_01.
passwd: all authentication tokens updated successfully.
Changing password for user user_02.
passwd: all authentication tokens updated successfully.
Changing password for user user_03.
passwd: all authentication tokens updated successfully.
Changing password for user user_04.
passwd: all authentication tokens updated successfully.
Changing password for user user_05.
passwd: all authentication tokens updated successfully.
Changing password for user user_06.
passwd: all authentication tokens updated successfully.
Changing password for user user_07.
passwd: all authentication tokens updated successfully.
Changing password for user user_08.
passwd: all authentication tokens updated successfully.
Changing password for user user_09.
passwd: all authentication tokens updated successfully.
endl
评论