Linux Shell脚本生成用户并授权

#!/bin/bash

dirpath="/opt/gjoy"
if [ ! -d ${dirpath} ]; then
  mkdir -p ${dirpath}
fi
cd ${dirpath}

pName=$(rpm -qa | grep 'expect')
if [ $? -eq 0 ]; then
       echo "软件包"expect"已经安装"
else
       echo "软件包"expect"没有安装"
	   #使用mkpasswd可以根据自己的定义来随意生成密码
	   yum -y install expect
fi

usergroup="erpgroup" 
username="erpadmin"
usepw=$(mkpasswd -l 15 -d 2 -c 2 -C 2 -s 2)

action="${1}"

case ${action} in
	"create")
		#创建用户组
		groupadd ${usergroup}
		#指定登录目录,创建用户并加入用户组
		useradd -d /home/${username} -m -g ${usergroup} ${username}
		#修改密码
		echo ${usepw} | passwd --stdin ${username}
		#打印账户信息
		echo "username=${username}, usergroup=${usergroup}, password=${usepw}" >> outputpw.txt
		#授权(root 权限)
		chmod -v u+w /etc/sudoers
		sed -i "/root	ALL=(ALL) 	ALL/a\\$username    ALL=(ALL)       NOPASSWD: ALL" /etc/sudoers
		chmod -v u-w /etc/sudoers
		;;
	"delete")
		echo "deleting ${username}"
		userdel -r ${username}
		groupdel ${usergroup}
		chmod -v u+w /etc/sudoers
		sed -i "/\\$username    ALL=(ALL)       NOPASSWD: ALL/d" /etc/sudoers
		chmod -v u-w /etc/sudoers
		rm -rf outputpw.txt
		;;
	*)
		echo "Usage: $0 [create|delete]"
		;;
esac
使用方法
chmod +x adduser.sh

创建用户
./adduser.sh create

删除用户
./adduser.sh delete

生成的用户名和密码会保存到/opt/gjoy/outputpw.txt
上一篇:CentOS 7 Suspend


下一篇:linux - shell , loop