1.下载
yum install -y expect
2.使用
#!/usr/bin/expect
spawn +command
expect {
"希望匹配到的元素" { send "希望输出的内容";exp_continue }
"希望匹配到的元素" { send "希望输出的内容" };
}
interact
spawn expect 内部命令,启动一个shell程序。
expect 期望哪些内容
””内输入希望匹配到的问题 ,\r 表示回车
send后的””内输入当遇到匹配到的问题时需要交互执行的动作
exp_continue,跳过循环,就继续下一条语句。
interact 允许用户交互
3.示例
Eg1: 用expect脚本实现远程登录
#!/usr/bin/expect
spawn ssh root@192.168.80.170
expect {
"password:" { send "liu13881044103\r"};
}
Interact
Eg1: expect+shell 实现批量推送密匙
ip.text:从机ip集合文件
192.168.80.170
keygen_expect.sh:主机执行文件
#!/bin/bash
if [ x"$1" = x ] ;then
echo "ip文件不存在"
exit
fi
/usr/bin/expect<<-EFO
spawn ssh-keygen -t rsa
expect {
"Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r";exp_continue};
"Overwrite (y/n)?" { send "y\r";exp_continue};
"Enter passphrase (empty for no passphrase):" { send "\r";exp_continue};
"Enter same passphrase again:" { send "\r";exp_continue};
}
EFO
while read ip;do
ping -c1 -w1 $ip
if [ $? -ne 0 ];then
echo "ping $ip is error"
continue
fi
/usr/bin/expect<<-EFO
spawn scp /root/.ssh/id_rsa.pub /root/install_keygen.sh root@$ip:/root/
expect {
"password:" { send "liu13881044103\r";exp_continue};
}
EFO
/usr/bin/expect<<-EFO
spawn ssh root@$ip "chmod a+x /root/install_keygen.sh; bash /root/install_keygen.sh"
expect {
"password:" { send "liu13881044103\r";exp_continue};
}
EFO
echo "create $ip ssh-keygen successful"
done<$1
install_keygen.sh 从机执行文件
#!/bin/bash
[ -e /root/.ssh/authorized_keys ]
if [ $? -ne 0 ];then
echo "/root/.ssh/authorized_keys not exist"
[ -e id_rsa.pub ]
if [ $? -ne 0 ];then
echo "id_rsa.pub not exist"
exit
fi
mkdir /root/.ssh &>/dev/null
if [ $? -eq 0 ];then
cat id_rsa.pub>>/root/.ssh/authorized_keys
status=$?
fi
else
[ -e id_rsa.pub ]
if [ $? -ne 0 ];then
echo "id_rsa.pub not exist"
exit
fi
if [ $? -eq 0 ];then
cat id_rsa.pub>>/root/.ssh/authorized_keys
status=$?
fi
fi
if [ $status -eq 0 ] ; then
echo 'successful'
else
echo 'error'
fi