博主大三Linux课程设计是一道题,如下:
使用shell脚本编程实现批量创建用户,删除用户,批量创建目录,目录权限添加
为了写这个课程设计,自己硬是把一本Linux操作系统书给看了一遍,也算是复习了一下Linux,最终完成了这次课程设计,这里把代码贴出来分享一下,因为是为了应对课程设计,所以很多细节都没有仔细打磨,单纯为了实现功能,不好的地方还请指出。
代码主要是针对题目进行编写分为5块
1.添加用户
2.删除用户
3.创建目录
4.删除目录
5.退出程序
#!/bin/bash
#filename:newuser.sh
#Display a menu
echo -------------
echo "1 adduser"
echo "2 deluser"
echo "3 createdir"
echo "4 deldir"
echo "5 exishell"
#Read and excute the user's selection
echo -n "Enter Choice:"
read CHOICE
case "$CHOICE" in
1)#add user
echo "Please enter the number of users you want to add"
read NUM
echo "Whether to create a user home directory? 1/0"
read CHOME
if [ $CHOME -eq 1 ]
then
udir="-m"
else
udir="-M"
fi
echo "Whether to set expiration time? 1/0"
read CDATE
if [ $CDATE -eq 1 ]
then
echo "Please enter the time MM/DD/YY"
read ETIME
if echo $ETIME |grep -Eq "[0-9]{2}/[0-9]{2}/[0-9]{2}" && date -d $ETIME +%x >/dev/null 2>&1
then
utime="-e $ETIME"
else
echo "Wrong date format"
exit 1
fi
else
utime=''
fi
echo "Whether user groups are set 1/0?"
read CGROUP
if [ $CGROUP -eq 1 ]
then
echo "Please enter the user group name"
read GNAME
#create group if not exists
egrep "^$GNAME" /etc/group >& /dev/null
if [ $? -ne 0 ]
then
echo "User groups that do not exist will be created automatically"
groupadd $GNAME
ugroup="-g $GNAME"
else
ugroup="-g $GNAME"
fi
else
ugroup=''
fi
#for i in `seq 1 $NUM`
for ((i=1;i<=$NUM;i++))
do
id -u user$i >/dev/null 2>&1
if [ $? -ne 0 ]
then
pw=`cat /dev/urandom | head -n 10 | md5sum | head -c 6` #Gets a 6-digit random number
useradd $udir $utime $ugroup user$i
echo "user$i $pw" >> /root/pw.txt #Write the account password to the file
echo "$pw" | passwd --stdin user$i
else
let NUM=NUM+1
fi
done
echo "add user successful";;
2)#del user
echo "Please enter the number of users to delete"
read DELNUM
uid=`awk -F ':' '{print $3}' /etc/passwd`
user=`awk -F ':' '{print $1}' /etc/passwd`
array=($user)
j=0
n=0
for i in $uid;do
if [ $i -gt 1000 ];then
if [ $n -lt $DELNUM ];then
if [ ! -d "/home/${array[$j]}" ]
then
userdel "${array[$j]}" #user dir not create
else
userdel -r "${array[$j]}"
fi
sed -i '1d' /root/pw.txt #del file user info
let n=n+1
else
break
fi
fi
let j=j+1
done
echo "del user success!!!";;
3)
echo "Please input you want create dir nums"
read DIRNUM
echo "Please set dir chmod (ug+rwx) u user g group"
read STR
for i in `seq 1 $DIRNUM`
do
mkdir /root/dir$i
chmod $STR /root/dir$i
done
echo "create successfull";;
4)
echo "Please input you want delete dir nums"
read DIRNUM
for i in `seq 1 $DIRNUM`
do
rm -rf /root/dir$i
done
echo "delete successfull";;
5) exit 1;;
*) echo "Sorry $CHOICE is not a valid choice"
exit 1;;
esac