shell---expect
1.expect的安装
[root@qfedu ~] yum -y install expect
2.expect的语法:
用法:
1)定义expect脚本执行的shell
#!/usr/bin/expect -----类似于#!/bin/bash
2)spawn
spawn是执行expect之后后执行的内部命令开启一个会话 #功能:用来执行shell的交互命令3)expect ---相当于捕捉
功能:判断输出结果是否包含某项字符串(相当于捕捉命令的返回的提示)。没有捕捉到则会断开,否则等待一段时间后返回,等待通过timeout设置
4)send
执行交互动作,将交互要执行的命令进行发送给交互指令,命令字符串结尾要加上“\r”,#---相当于回车
5)interact
执行完后保持交互状态,需要等待手动退出交互状态,如果不加这一项,交互完成会自动退出
6)exp_continue
继续执行接下来的操作
7)timeout
返回设置超时时间(秒)
如果添加interact参数将会等待我们手动交互进行退出。如果不加interact参数在登录成功之后会立刻退出。
expect eof #也是直接退出expect模式
1.
vim expect01.sh#!/usr/bin/expect
spawn ssh root@192.168.246.115expect {"yes/no" { send "yes\r"; exp_continue }"password:" { send "1\r" };
}
interactchmod +x expect01.sh./expect01.sh
2.
设置变量与进行传参的方式
#注意:expect环境中设置变量用set,识别不了bash方式定义的变量 vim expect01.sh#!/usr/bin/expect
set user root
set pass 1
set ip [ lindex $argv 0 ] #expect固定写法,从0开始,第一个位置参数,相当于shell中的$1
set timeout 10spawn ssh $user@$ip
expect {"yes/no" { send "yes\r"; exp_continue }"password:" { send "$pass\r" };
}
interact./expect01.sh 10.7.49.27
练习
进行批量推送公钥实现免密连接,ping通一个ip地址连接一个ip
vim getip_push.sh#!/usr/bin/bash
#判断expect命令是否安装
rpm -qa expect &> /dev/null
if [ $? -ne 0 ];thenyum install -y expect
fi#判断主机下面是否生成秘钥,如果没有生成秘钥
if [ ! -f ~/.ssh/id_rsa ];thenssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
fi#循环执行获取up状态的ip地址。
for i in {2..254}
do{ip=192.168.198.$iping -c1 $ip &> /dev/nullif [ $? -eq 0 ];thenecho "$ip" >> up_ip.txtset timeout 10/usr/bin/expect <<-EOF #shell脚本中调用expect命令spawn ssh-copy-id $ipexpect {"yes/no" { send "yes\r"; exp_continue }"password:" { send "1\r" };}expect eofEOFfi } &
wait
done
echo "finish..."chmod +x getip_push.sh ./getip_push.sh
[root@mysql-server script]# cat shuzu.sh
#!/bin/bash
server_ip=(192.168.209.166 192.168.209.168 192.168.209.169)
server_name=(web-1 web-2 mysql-server)
for (( i=0; i<${#server_ip[@]}; i++ ))
doecho $i-----${server_ip[i]}-----${server_name[i]}
done
echo "请输入要连接的序号: " && read n
if [[ $n -ge 0 && $n -lt ${#server_ip[@]} ]];thenecho "正在链接${server_ip[n]}"sleep 1/root/expect/expect.sh ${server_ip[n]}
elseecho "请输入范围内的序号..."sleep 1
fi[root@bogon ~]# cat exp.sh
#!/usr/bin/expect
spawn ssh $user@$ip
expect {"yes/no" { send "yes\r";exp_continue }"password:" { send "1\r"};}
interact