你好,游客 登录 注册 搜索
背景:
阅读新闻

shell 批量添加用户健壮版

[日期:2013-11-30] 来源:Linux社区  作者:gccmx [字体:大 中 小]

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

#!/bin/bash
#load system functions
[ -f /etc/init.d/functions ] && . /etc/init.d/functions
for i in `seq -w 10`
do
        #generate passwd,8 random chars
        passwd=`echo $(date +%t%N)$RANDOM|md5sum|cut -c 2-9`
        #check wheather the username is in the /etc/passwd
        #important awk use the shell variable
        check=`awk -F ':' '/^'gccmx$i'/ {print $1}' /etc/passwd`
        if [ -z "$check" ];then
                useradd gccmx$i &>/dev/null && user_status=$?
                echo $passwd | passwd --stdin gccmx$i &>/dev/null && passwd_status=$?
        else
                user_status=1
                passwd_status=1
        fi
        if [ "$user_status" -eq 0 -a "$passwd_status" -eq 0 ];then
                action "The user gccmx$i is add successfully!" /bin/true
                echo -e "username:gccmx${i}\tpassword:${passwd}" >>/tmp/userinfo.txt
        else
                action "The user gccmx$i is add faild!" /bin/false
                echo -e "username:gccmx${i}\tpassword:${passwd}" >>/tmp/faild_info.txt
        fi
        unset user_status && unset passwd_status
        sleep 1
done

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

相关阅读:

自动备份脚本 Linux shell 第二版 http://www.linuxidc.com/Linux/2012-11/74219.htm

Linux/Unix shell 脚本中调用SQL,RMAN脚本 http://www.linuxidc.com/Linux/2012-09/70310.htm

Linux/Unix shell sql 之间传递变量 http://www.linuxidc.com/Linux/2013-01/78811.htm

Linux命令之sleep - 延迟指定时间 http://www.linuxidc.com/Linux/2011-04/34758.htm

Linux下Shell编程——sed命令基本用法 http://www.linuxidc.com/Linux/2013-06/85526.htm

linux
相关资讯       shell批量添加用户  shell添加用户 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款