[root@localhost ~]# cat
list.txt
#ip name passwd
192.168.128.10 zhangsan
111111
192.168.128.11 lisi 222222
192.168.128.12 wangwu
333333
[root@localhost ~]#cat
setpass.sh
#!/bin/bash
answer="yes"
rootpass="123456"
cat list.txt|grep -v "#" |
while read ip user passwd
do
for i in $ip
do
expect
<
set timeout -1
spawn ssh $i "useradd
$user;echo -e "$passwdn$passwd" | passwd $user"
#spawn ssh $i "useradd
$user;echo "$passwd" |passwd --stdin $user" #第二种方式
expect "(yes/no)?"
{
send "$answerr"
expect
"password:"
send
"$rootpassr"
} "password:" {send
"$rootpassr"} "*host" {exit 1}
expect eof
EOF
done
done
在这里和前面很多脚本中都用到了read命令,简单说一下:
read一个很常用的交互式命令,只要存在条件判断的shell中都能用到,根据需要既可手动交互也可以进行自动交互,下面演示一下case,if,while等各种控制流结构中使用。
基本使用:单个变量赋值
[root@localhost ~]# read name
zhangsan
[root@localhost ~]#
[root@localhost ~]# echo $name
zhangsan
给多个变量赋值:
[root@localhost ~]# read name age
zhangsan 20
[root@localhost ~]# echo $name $age
zhangsan 20
case条件判断:
[root@localhost ~]#cat case.sh
#!/bin/bash
read -p "input you choice(yes/no):" answer
case $answer in
yes|YES)
echo "you choice $answer"
;;
no|NO)
echo "you choice $answer"
;;
*)
echo "pls input yes or
no!"
;;
esac
[root@localhost ~]# sh case.sh
input you choice(yes/no):yes
you choice yes
[root@localhost ~]# sh case.sh
input you choice(yes/no):no
you choice no
[root@localhost ~]# sh case.sh
input you choice(yes/no):dsa
pls input yes or no!
if条件判断,与case基本相同:
[root@localhost ~]# more if.sh
#!/bin/bash
read -p "input you number:" num
if [ $num -eq 1 ]
then
echo "you input is $num"
else
echo "input wrong"
fi
[root@localhost ~]# sh if.sh
input you number:1
you input is 1
[root@localhost ~]# sh if.sh
input you number:2
input wrong
while read语句:最常用的结构,可用于一些需要批量执行的操作,例如上面的脚本
[root@localhost ~]# cat list.txt
#ip name
passwd
192.168.128.10 zhangsan 111111
192.168.128.11 lisi 222222
192.168.128.12 wangwu 333333
[root@localhost ~]# cat read.sh
cat list.txt|while read line
do
echo $line
done
另一种方式:
[root@localhost ~]# cat read-1.sh
while read line
do
echo $line
done