歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 批量添加用戶的shell腳本

批量添加用戶的shell腳本

日期:2017/3/3 15:59:56   编辑:關於Linux

題目要求:通過shell編程,實現批量添加用戶。

保存為任意文件名:給x權限

不加任何參數,則為添加user1.user2.user3....user10,密碼=用戶名

加參數例:command -a test 20 命令 -a添加 test是用戶頭 20是添加數量(一次添加最多不得大於100個,下面代碼可以自己改)

command -d test 刪除系統中用戶名以test開頭的,後跟數字的用戶名,不加test,則默認刪除user1.user2.user3...這類用戶...慎用...

#!/bin/bash
U=${2:-user}
Num=${3:-10}
Res=`grep -o "^\<$U[0-9]\{1,\}\>" /etc/passwd|grep -o "[0-9]\{1,\}"|sort -n|tail -1`
Res1=${Res:-0}
Res2=$((Res1+Num))
ALL=`cat /etc/passwd|wc -l`
if [[ -z $1 || $1 == '-a' && ! -z $2 && $3 -le 100 ]];then
        for((i=${Res1};i<=${Res2};i++))
        do
                if [[ $i -ne 0 ]];then
                        useradd  ${U}$i &> /dev/null
                        echo "${U}$i"|passwd --stdin ${U}$i &> /dev/null
                fi 
        done
                AALL=`cat /etc/passwd|wc -l`
                echo "Add user number is $((AALL-ALL))"
elif [[ ! -z $1 && "$1" = '-d' ]] ;then
        for((i=${Res1};i>=1;i--))
        do
                Res3=`grep -o "^\<${U}${i}\>" /etc/passwd`
    
                if [[ -n $Res3 && "${U}$i" == "$Res3" ]];then
                        userdel -r  ${U}$i &> /dev/null
                fi
        done
                DALL=`cat /etc/passwd|wc -l`
                echo "Del user number is $((ALL-DALL))"
else
        echo -e "\033[33;5merror!\033[0m Please input none or -a or -d"
fi

URL:http://www.bianceng.cn/OS/Linux/201410/45684.htm

Copyright © Linux教程網 All Rights Reserved