需求:在服务器上批量安装agent程序,并使用root用户启动程序。
为什么要用expect
expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
1.实现交互式执行命令,将程序包发送到指定服务器
注:这里的ip.txt文件存储服务器ip
#! /bin/bash
cat ip.txt | while read line
do
(
/usr/bin/expect << EOF
set time 20
spawn scp /home/file_agent.tar.gz dcloud@$line:/home/
expect {
"*yes/no*"
{ send "yes\r";exp_continue }
"*password:"
{ send "password\r"}
}
expect eof
EOF
) &>/dev/null
if [ $? -eq 0 ]
then
echo "复制文件到$line成功!"
else
echo "复制文件到$line失败!"
fi
done
2.解压程序包
注:执行方式:*.sh command
#! /bin/bash
remote_server()
{
hosts=`sed -n '/^[^#]/p' ip.txt`
for host in $hosts
do
echo HOST $host
(
/usr/bin/expect << EOF
spawn ssh dcloud@$host "$@"
expect {
"(*yes/no*)?"
{send "yes\r";exp_continue}
"password:"
{send "password\r"}
}
expect eof
EOF
) >>xinxi.txt
done
return 0
}
#echo -e "\033[31m执行命令 : $@ \033[0m"
remote_server "$@"
3.此脚本目的是实现将目标服务器切换为root用户并启动程序自身启动脚本
#! /bin/bash
/usr/bin/expect << EOF
spawn su -
expect {
":"
{send "password\r"}
}
expect -re "\](\$|#) "
send "bash /home/file/bin/file_agent.sh\r" #这里为程序本身的启动脚本
expect eof
EOF
4.将上一个脚本发送到指定服务器并执行
#! /bin/bash
scp_sh()
{
cat ip.txt | while read line
do
(
/usr/bin/expect << EOF
spawn scp /home/start_file.sh dcloud@$line:/home/ #这里的start_file.sh为上一个脚本
expect {
"*yes/no*"
{ send "yes\r";exp_continue }
"password:"
{send "password\r"}
}
expect eof
EOF
)
done
}
start_sh()
{
cat ip.txt | while read line
do
/usr/bin/expect << EOF
spawn ssh dcloud@$line
expect {
"*yes/no*"
{ send "yes\r";exp_continue }
"password:"
{send "password\r"}
}
expect -re "\](\$|#) "
send "bash /home/start_file.sh\r"
expect eof
EOF
done
}
scp_sh
start_sh
except总结:
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间