[iyunv@localhost shell.sh]# ./test.sh 192.168.1.106 root jiajie
spawn ssh -l root 192.168.1.106root@192.168.1.106's password:
Last login: Sat Sep 9 04:10:46 2017 from web
[iyunv@localhost ~]# useradd jj
[iyunv@localhost ~]# echo jiajie|passwd --stdin jj
Changing password for user jj.
passwd: all authentication tokens updated successfully.
[iyunv@localhost ~]# exit
logout
Connection to 192.168.1.106 closed.
[iyunv@localhost shell.sh]#
五. shell脚本调用expect(2)
通过shell脚本通过调用expect脚本实现批量认证:
expect脚本:
[iyunv@localhost shell.sh]# vim scp.exp
#!/usr/bin/expect
if {$argc!=3} {
send_user "Usage:expect need three arguments lisk thks:file host dir\n"
exit 1
}
set srcname [lindex $argv 0]
set hostname [lindex $argv 1]
set destname [lindex $argv 2]
set password "jiajie"
spawn scp $srcname root@$hostname:$destnameset
timeout 30
expect {
# -timeout 2
"yes/no" {send "yes\r";exp_continue}
"*password:" {send "$password\r"}
# timeout {puts "expect connect failure,please contact admin.";return}}
expect eofexit -onexit {
send_user "Jobs has finished,Goodbye.\n"
}
shell脚本:
[iyunv@localhost shell.sh]# vim scp.sh
#!/bin/bash
if [[ "$#" != "2" ]];then
echo "Usage:$0 src_filename des_filename"
exit 0
fi
IP_LIST=(
192.168.1.106
192.168.1.170
192.168.1.10)
. /etc/init.d/functions
for ip in ${IP_LIST
}
do
expect scp.exp $1 $ip $2 &> /dev/null
if [ $? -eq 0 ];then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done
scp.sh脚本通过调用expect脚本来实现分发功能。执行结果如下:
[iyunv@localhost shell.sh]# sh scp.sh /etc/fstab /tmp/
192.168.1.106 [ OK ]
192.168.1.170 [ OK ]
192.168.1.10 [FAILED]