055-批量建立任意用戶在主機中

工做中確定會有建立用戶的需求,少的咱們能夠建立,可是用戶多了呢?bash

1.腳本

如下陳述解決:服務器

a.如何將輸入的用戶名和密碼引用到腳本ssh

b.如何將用戶名和密碼顯現出來而且打印出來oop

c.如何判斷已經存在的用戶,無需重複建立密碼spa

#!/bin/bash
USERADD=/usr/sbin/useradd
PASSWD=/usr/bin/passwd
CUT=/bin/CUT
USER_INFO=/server/scripts/addusers.txt

while read LINES
do
  USERNAME=` echo $LINES |cut -f1 -d' '`
  PASSWORD=` echo $LINES |cut -f2 -d' '`
  useradd $USERNAME
  if [ $? -ne 0 ]
then
  echo "$USERNAME is exists"
else
  echo  $PASSWORD | passwd --stdin $USERNAME
fi


done < $USER_INFO

addusers.txt中文件的內容code

[root@cnsz142728 scripts]# cat addusers.txt 
mumu 123456
kaka 123456
lele 123456

 

2.分析拆解過程

2.1 用for語句能夠達到目的麼?

[root@cnsz142728 scripts]# cat useradd_for01.sh 
#!/bin/bash
for LINES in `cat addusers.txt`
do
 echo $LINES
 let COUNT+=1
done
echo 
echo $0 looped $COUNT times
[root@cnsz142728 scripts]# ./useradd_for01.sh 
mumu
123456
kaka
123456
lele
123456

./useradd_for01.sh looped 6 times

2.2 for語句不行,改用while語句

[root@cnsz142728 scripts]# ./useradd_for01.sh 
mumu
123456
kaka
123456
lele
123456

./useradd_for01.sh looped 6 times
[root@cnsz142728 scripts]# cat useradd_while01.sh 
#!/bin/bash
COUNT=0
while read LINES
do
   echo  $LINES
   let COUNT+=1
   done < addusers.txt
echo
echo "$0 looped $COUNT times"
[root@cnsz142728 scripts]# ./useradd_while01.sh 
mumu 123456
kaka 123456
lele 123456

./useradd_while01.sh looped 3 times

2.3 顯示出用戶名和密碼

[root@cnsz142728 scripts]# cat useradd_while02.sh 
#!/bin/bash
while read LINES
do
   USERNAME=`echo $LINES | cut -f1 -d' ' `
   PASSWORD=`echo $LINES | cut -f2 -d ' '`
   echo -n "USERNAME:$USERNAME PASSWORD:$PASSWORD"
  echo 
done < addusers.txt
  
[root@cnsz142728 scripts]# ./useradd_while02.sh 
USERNAME:mumu PASSWORD:123456
USERNAME:kaka PASSWORD:123456
USERNAME:lele PASSWORD:123456

 

拓展:結合ssh分發腳本,事先編寫好,就可以達到多臺服務器操做server

相關文章
相關標籤/搜索