歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> SHELL編程

Linux下shell調用expect進行批量升級

執行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

Copyright © Linux教程網 All Rights Reserved