参考《鸟哥的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. 拿到你所创建的用户及其初始密码,该用户登录后会被强制要求更改密码
    在这里插入图片描述

原文地址:https://blog.csdn.net/qq_43656353/article/details/134628421

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_586.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注