需求:在服務(wù)器上批量安裝agent程序,并使用root用戶啟動(dòng)程序膘魄。
為什么要用expect
expect是一個(gè)自動(dòng)化交互套件乌逐,主要應(yīng)用于執(zhí)行命令和程序時(shí),系統(tǒng)以交互形式要求輸入指定字符串创葡,實(shí)現(xiàn)交互通信浙踢。
1.實(shí)現(xiàn)交互式執(zhí)行命令,將程序包發(fā)送到指定服務(wù)器
注:這里的ip.txt文件存儲服務(wù)器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 "復(fù)制文件到$line成功灿渴!"
else
echo "復(fù)制文件到$line失斅宀ā!"
fi
done
2.解壓程序包
注:執(zhí)行方式:*.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執(zhí)行命令 : $@ \033[0m"
remote_server "$@"
3.此腳本目的是實(shí)現(xiàn)將目標(biāo)服務(wù)器切換為root用戶并啟動(dòng)程序自身啟動(dòng)腳本
#! /bin/bash
/usr/bin/expect << EOF
spawn su -
expect {
":"
{send "password\r"}
}
expect -re "\](\$|#) "
send "bash /home/file/bin/file_agent.sh\r" #這里為程序本身的啟動(dòng)腳本
expect eof
EOF
4.將上一個(gè)腳本發(fā)送到指定服務(wù)器并執(zhí)行
#! /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為上一個(gè)腳本
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總結(jié):
spawn 交互程序開始后面跟命令或者指定程序
expect 獲取匹配信息匹配成功則執(zhí)行expect后面的程序動(dòng)作
send exp_send 用于發(fā)送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用來打印輸出 相當(dāng)于shell中的echo
exit 退出expect腳本
eof expect執(zhí)行結(jié)束 退出
set 定義變量
puts 輸出變量
set timeout 設(shè)置超時(shí)時(shí)間