歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell腳本:批量添加用戶,並設置隨機字符為密碼

Shell腳本:批量添加用戶,並設置隨機字符為密碼

日期:2017/3/1 9:25:49   编辑:SHELL編程

練習shell腳本題目:寫一個腳本,實現批量添加20個用戶,用戶名為user1-20,密碼為user後面跟5個隨機字符;

之前練習過批量創建用戶,使用for循環就可以實現,這次多了一個需求,設置用戶密碼,密碼為user後面跟5個隨機字符。思路為:創建用戶當然還是使用for循環,隨機字符需要研究一下怎麼生成,怎麼在腳本裡面設置密碼?

下面是經過我測試多次,實現題目需求的腳本,大家有更好的可以貼出來,共同學習。

[root@localhost ~]# cat user.sh
#!/bin/bash
#writen by mofansheng @2015-08-04
for i in `seq 1 20`
do
  pw=`echo $[$RANDOM]|md5sum|cut -c 1-5`
  useradd user$i
  echo "user$i $pw" >> /root/pw.txt
  echo "user$pw" |passwd --stdin user$i
done

提醒注意:生成隨機密碼後直接給用戶設定了,但是我並不知道隨機密碼是什麼啊。所以加了一個隨機密碼定向到一個文件中,方便管理。格式為:用戶名 後面跟隨機字符;舉例如下:

[root@localhost ~]# cat pw.txt
user1 3e9db
user2 febb6
user3 43c55

其他生成隨機字符的方法:

1:生成的隨機字符為字母加數字組合

[root@localhost ~]# cat /dev/urandom | head -1|md5sum |head -c 5
cf93d
[root@localhost ~]# cat /dev/urandom | head -1|md5sum |head -c 5
75217


2:生成的隨機字符包含特殊字母

[root@localhost ~]# cat /dev/urandom | strings -n 5 | head -n 1
O4%"G
[root@localhost ~]# cat /dev/urandom | strings -n 5 | head -n 1
mMSxu

Copyright © Linux教程網 All Rights Reserved