Linux环境下自动化创建大量的账号

参考《鸟哥的Linux私房菜基础篇第四版》13.7.2节微调而成:

下面脚本的目的是为服务器的管理员自动化创建大量的账号,节省生命。

#!/bin/bash
# This shell script will create amount of Linux login accounts for you.
# 1. check the "accountadd.txt" file exist? you mush create that file manually.
# one account name one line in the "accountadd.txt" file.
# 2. use openssl to create users password.
# 3. user must change his password in his first login.
# 4. more option.
# 2023/11/26	chen peng
export PATH
# 0. userinput
pwmech="openssl"
# 1. check the accountadd.txt file
if [ ! -f accountadd.txt ]; then
	echo -e "There is no accountadd.txt file, stop here."
	exit 1
fi
rm -f outputpw.txt	# clear outputpw.txt to place new account's password
usernames=$(cat accountadd.txt)
for username in $usernames
do
	useradd -m -s /bin/bash ${username}	 # new username (default create home directory and use /bin/bash)
	if [ "$pwmech" == "openssl" ]; then
		usepw=$(openssl rand -base64 6)	 # it will output a random string that's 8 characters long
	#else
	#	usepw=$username
	fi
	echo "$username:$usepw" | chpasswd 	 # new password
	chage -d 0 $username 			     # force password change
	echo "username=$username, password=$usepw" >> outputpw.txt
done

运行命令之前的条件:

  1. 手动在该脚本(accountadd.sh)所在目录下创建一个文本文件accountadd.txt,文件的内容是每一行代表待创建的用户名,例如我这次要一次性创建两个账户,它们分别是st01,st02,即:
    在这里插入图片描述
  2. 获得root权限,利用sudo -i 并且输入自己账户的密码,然后进入脚本的目录。

运行命令

  1. 输入脚本执行命令,加入选项-x能够看见脚本执行的过程以方便debug
    bash -x accountadd.sh
    
    输出如下:
    + export PATH
    + pwmech=openssl
    + '[' '!' -f accountadd.txt ']'
    + rm -f outputpw.txt
    ++ cat accountadd.txt
    + usernames='st01
    st02'
    + for username in $usernames
    + useradd -m -s /bin/bash st01
    + '[' openssl == openssl ']'
    ++ openssl rand -base64 6
    + usepw=dQX+awTv
    + echo st01:dQX+awTv
    + chpasswd
    + chage -d 0 st01
    + echo 'username=st01, password=dQX+awTv'
    + for username in $usernames
    + useradd -m -s /bin/bash st02
    + '[' openssl == openssl ']'
    ++ openssl rand -base64 6
    + usepw=H8zNuqFI
    + echo st02:H8zNuqFI
    + chpasswd
    + chage -d 0 st02
    + echo 'username=st02, password=H8zNuqFI'
    
  2. 拿到你所创建的用户及其初始密码,该用户登录后会被强制要求更改密码。
    在这里插入图片描述
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ocodotial

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值