1. 程式人生 > >Shell開發批量創建Linux賬戶和隨機8位數密碼

Shell開發批量創建Linux賬戶和隨機8位數密碼

$? pts 用戶 test txt shell 要求 roo 批量

需求:批量創建10個系統賬號,如:test-01到test-10,並且為每一個用戶設置密碼為隨機8位數,同時將創建成功的賬號對應密碼保存在/tmp/user.txt裏,失敗則把失敗的賬號對應密碼保存到/tmp/fail_user.txt裏

1)批量創建系統賬號,沒什麽特殊的直接使用useradd結合變量
2)隨機8位數密碼,需要使用到產生隨機數的命令,在演示腳本中作者用了以下三條命令結合使用,操作如下:

[root@jason scripts]# echo $(date +%t%N)$RANDOM|md5sum 
142470e2de821875c8e002ba0d2bf4e5  - 
提示:作者分別使用了date,和系統環境變量RANDOM跟md5sum來結合產生隨機數

3)前面要求密碼為隨機8位數,但是前者兩個命令結合md5sum會產生128位的固定隨機數,文中使用cut命令,來抓取8位隨機數,操作如下:

[root@jason ~]# echo $(date +%t%N)$RANDOM|md5sum |cut -c 2-9
3e05cfe6

4)腳本展示

[root@jason scripts]# cat adduser.sh 
#!/bin/sh
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions || exit 1
>/tmp/user.txt
for n in $(seq -w 10)
do
 passwd=`echo $(date +%s%n)$RANDOM|md5sum |cut -c 2-9`
 useradd test-$n >&/dev/null && user_status=$?
 echo "$passwd"|passwd --stdin test-$n >&/dev/null  && pass_status=$?
if [ $user_status -eq 0 -a $pass_status -eq 0 ];then
        action "adduser test-$n" /bin/true
        echo -e "user:\ttest-$n passwd:$passwd" >>/tmp/user.txt
 else
        action "adduser test-$n" /bin/false
        echo -e "user:\ttest-$n passwd:$passwd" >>/tmp/fail_user.txt
fi
done

5)腳本測試

#運行腳本
[root@jason scripts]# sh adduser.sh     
adduser test-01                                            [  OK  ]
adduser test-02                                            [  OK  ]
adduser test-03                                            [  OK  ]
adduser test-04                                            [  OK  ]
adduser test-05                                            [  OK  ]
adduser test-06                                            [  OK  ]
adduser test-07                                            [  OK  ]
adduser test-08                                            [  OK  ]
adduser test-09                                            [  OK  ]
adduser test-10                                            [  OK  ]

#查看創建成功的用戶對應的密碼
[root@jason scripts]# cat /tmp/user.txt 
user:   test-01 passwd:cd2e36b9
user:   test-02 passwd:98ceb8f4
user:   test-03 passwd:813c5067
user:   test-04 passwd:20e3c58e
user:   test-05 passwd:ed0d93f9
user:   test-06 passwd:67aadb88
user:   test-07 passwd:f399ce9b
user:   test-08 passwd:f32be6f9
user:   test-09 passwd:bfa0cc7a
user:   test-10 passwd:25b6553e

#查看/etc/passwd文件
[root@jason scripts]# tail -10 /etc/passwd
test-01:x:533:533::/home/test-01:/bin/bash
test-02:x:534:534::/home/test-02:/bin/bash
test-03:x:535:535::/home/test-03:/bin/bash
test-04:x:536:536::/home/test-04:/bin/bash
test-05:x:537:537::/home/test-05:/bin/bash
test-06:x:538:538::/home/test-06:/bin/bash
test-07:x:539:539::/home/test-07:/bin/bash
test-08:x:540:540::/home/test-08:/bin/bash
test-09:x:541:541::/home/test-09:/bin/bash
test-10:x:542:542::/home/test-10:/bin/bash

Shell開發批量創建Linux賬戶和隨機8位數密碼