shell 批量添加用户健壮版

网上传说,曾经有一道迅雷的笔试题,批量添加用户。做法很简单,有个小小的知识点。如何无交互的为用户设置密码。有两种方案:1、expect 2、passwd –stdin 。第一种通用,第二种非redhat相关版本可能无法使用。大道至简,用第二种。也看到过网上的相关脚本。感觉不太完善,至少,如果添加的用户中,原本有一个已经存在,那么怎么办。很多人都没有处理。对于一个有代码洁癖的Coder。我决定自己写一个。上代码:

#!/bin/bash#load system functions[ -f /etc/init.d/functions ] && . /etc/init.d/functionsfor i in `seq -w 10`do#generate passwd,8 random charspasswd=`echo $(date +%t%N)$RANDOM|md5sum|cut -c 2-9`#check wheather the username is in the /etc/passwd#important awk use the shell variablecheck=`awk -F ‘:’ ‘/^’gccmx$i’/ {print $1}’ /etc/passwd`if [ -z “$check” ];thenuseradd gccmx$i &>/dev/null && user_status=$?echo $passwd | passwd –stdin gccmx$i &>/dev/null && passwd_status=$?elseuser_status=1passwd_status=1fiif [ “$user_status” -eq 0 -a “$passwd_status” -eq 0 ];thenaction “The user gccmx$i is add successfully!” /bin/trueecho -e “username:gccmx${i}\tpassword:${passwd}” >>/tmp/userinfo.txtelseaction “The user gccmx$i is add faild!” /bin/falseecho -e “username:gccmx${i}\tpassword:${passwd}” >>/tmp/faild_info.txtfiunset user_status && unset passwd_statussleep 1done

运行效果(gccmx05,,已经存在,所以添加失败,用户名密码信息存储在/tmp/user_info.txt里):

都会有回报,愿你天天开心。

shell 批量添加用户健壮版

相关文章:

你感兴趣的文章:

标签云: