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,即:
    Linux环境下自动化创建大量的账号_第1张图片
  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. 拿到你所创建的用户及其初始密码,该用户登录后会被强制要求更改密码。
    Linux环境下自动化创建大量的账号_第2张图片

你可能感兴趣的:(电脑配置相关,linux,自动化,chrome)