Linux下shell调用expect进行批量升级

来源:互联网 发布:芬兰 桑拿日 知乎 编辑:程序博客网 时间:2024/04/28 17:32

        执行main.sh脚本即可实现无手执对hostname中各IP机器进行updatefilename升级包的升级。tcl和expect压缩包放在相同路径下,$TSMIS_ROOT为环境变量。

CopyFile.exp文件:

#!/usr/bin/expect -f
#输入分析仪ip以及需要上传的文件名和TSMIS_ROOT环境变量
set ip [lindex $argv 0]
set localfile [lindex $argv 1]
set  TSMIS_ROOT  [lindex $argv 2]

#scp拷贝需要传输的文件到指定目录,并且跳过手动输入部分
spawn scp -r $localfile root@$ip:$TSMIS_ROOT/tmp/$localfile
set timeout 300
expect {
 "yes/no"  {send "yes\r" ; exp_continue}
 "*assword:" {send "111111\n"}
 }
set timeout 300
send "exit\r"
expect eof

 

 

 

RunUpdate.exp文件:

#!/usr/bin/expect -f

set ip [lindex $argv 0]
set updatefile [lindex $argv 1]
set TSMIS_ROOT [lindex  $argv 2]

spawn ssh root@$ip
set timeout 300
expect "*assword:" { send "111111\n" }
set timeout 300
expect "#"
send "cd $TSMIS_ROOT/tmp\r"
set timeout 300
expect "#"
send "tar -zxvf $updatefile.tar.gz\r"
set timeout 300
expect "#"
send "cd $updatefile\r"
set timeout 300
expect "#"
send "sh $TSMIS_ROOT/bin/mykillproc.sh\r"
set timeout 300
expect "#"
send "sh *pdate.sh\r"
set timeout 300
expect "#"
send "reboot\r"
set timeout 300
expect "#"
send "exit\r"

expect eof

 

 

main.sh文件:

#Input TS/VAR IP into ' ',use "," to seperate them. Ex: hostlist:'192.168.10.178,192.168.10.179,192.168.10.180'
hostlist='192.168.10.176,192.168.10.171'

#Input update packet into ' '. Ex : updatefilename='update120821.tar.gz'
updatefilename='update120821.tar.gz'

chmod 777 *

#获取当前路径
cur_dir=$(pwd)

#判断expect是否已经安装
if [ -f "/usr/bin/expect" ];  then
 echo "/usr/bin/expect existed"
else
#安装expect环境
tar -zxvf tcl8.4.19-src.tar.gz
tar -zxvf expect-5.43.0.tar.gz
mv  tcl8.4.19  $TSMIS_ROOT/tcl8.4.19  -f
mv expect-5.43 $TSMIS_ROOT/expect-5.4.3 -f

#tcl安装
cd  $TSMIS_ROOT/tcl8.4.19/unix
./configure
make
make install
sleep 1
echo "Install tcl succeed !"

#expect安装
cd  $TSMIS_ROOT/expect-5.4.3
./configure --with-tclinclude=$TSMIS_ROOT/tcl8.4.19/generic --with-tclconfig=/usr/local/lib/  
make
make install
sleep 1
echo "Install  expect  succeed !"

#将expect可执行文件复制到/usr/bin目录下
cp /usr/local/bin/expect  /usr/bin/  -f

fi

#进入之前路径
cd $cur_dir

#获取当前时间
NOW=`date "+%Y-%m-%d %H:%M:%S"`
echo "$NOW " >$TSMIS_ROOT/tmp/UpdateFailed.log

#设置IFS分割字符
IFS=','
#循环升级
for host in $hostlist

do
echo "Sending updatepacket to $host ..."

RESULT=`ping -c 2 $host|grep 'ttl'`
if [ -z "$RESULT" ] ; then
#网络不通时,打印相关日志
echo "Can't connect to $host"  >>$TSMIS_ROOT/tmp/UpdateFailed.log
echo "##########Can't connect to $host!!!##########"

else
#网络畅通,则进行下一步操作
./CopyFiles.exp $host $updatefilename $TSMIS_ROOT
echo "Copy Files finished"

#在各个分析仪上运行升级包
./RunUpdate.exp $host ${updatefilename//.tar.gz/} $TSMIS_ROOT 
echo "$host update finished!!!"

fi

sleep 1

done

echo "All update finished"

rm -rf  $cur_dir/tcl8.4.19
rm -rf   $cur_dir/expect-5.43