expect交互shell及一键部署服务

安装expect

yum install expect
expect -v

简单登陆命令

[root@localhost xxxx]# cat ssh.exp 
#!/usr/bin/expect 
set timeout 30
spawn ssh [email protected]
expect {
"*yes/no" {send "yes\r"; exp_continue}
"password:" {send "cc0214\r"}
}
interact   //放弃控制,可以手工操作

在shell脚本中执行

 expect -c   在命令行运行expect 脚本

 shell中使用expect -c "expect脚本内容"来完成嵌套。

[root@localhost xxxx]# cat jump.sh 
#!/bin/sh

echo "------------登陆···········"
expect -c "
   spawn ssh [email protected]
   expect {
                \"*(yes/no)?\"
                {
                        send \"yes\n\"
                        expect \"password:\" {
                                send \"cc0214\n\"
                        }
                }
                \"*password:\"
                {
                        send \"cc0214\n\"
                }
    }
interact "

只在另端执行命令(复制,或者执行他端shell)

echo "------------部署项目···········"

function exe()  //定义函数
{
expect -c "
        $1
        set timeout 300
        expect {
                \"*(yes/no)?\"
                {
                        send \"yes\n\"
                        expect \"password:\" {
                                send \"cc0214\n\"
                        }
                }
                \"*password:\"
                {
                        send \"cc0214\n\"
                }
        }
       expect eof
"
}

exe "spawn scp /home/wangdong/1.txt [email protected]:/home/wx/1.txt"  //传递执行命令参数

shell中多行expect命令的写法

expect<<-EOF
spawn xxxx
set timeout 10
expect "password"
expect eof
EOF


//*****或者

expect <

重启所有接tomcat

#!/bin/bash
echo "-----------start stop--------------"
for i in {9001..9015}
do
	/home/weihu/tomcat/$i/bin/shutdown.sh
done

sleep 5

ps -ef | grep "/home/weihu/tomcat/90*" |grep -v grep |awk '{print $2}'|xargs kill -9


for i in {9001..9015}
do
	sleep 2
        /home/weihu/tomcat/$i/bin/startup.sh
done

 

echo "--------deployServer-begin------------"

arrserver=(9001 9002 9003 9004 9005)
for ((i=0;i<${#arrserver[@]};i++))
do
    sh /home/wx/tomcat/${arrserver[$i]}/bin/startup.sh
    echo "${arrserver[$i]}:successful start tomcat!!"
done



***********************************************************

#!/bin/bash
echo "--------deployServer-begin------------"
arrserver=(9001 9002 9003 9004 9005)
for ((i=0;i<${#arrserver[@]};i++))
do
    rm -rf /home/wx/tomcat/${arrserver[$i]}/webapps/test.txt
    echo "${arrserver[$i]}: delete successful !!"
done


for ((i=0;i<${#arrserver[@]};i++))
do
    cp -rf  /home/wx/tomcat/test.txt /home/wx/tomcat/${arrserver[$i]}/webapps
    echo "${arrserver[$i]}: war deploy successful !!"
done


#tomcat进程
tomcatPid=`ps -ef | grep tomcat | grep -v grep | awk '{print $2}'`
length=${#tomcatPid[*]}
 
if [ $length -gt 0 ]
  then
   for i in $tomcatPid
    do
     `kill -9 $i`
     echo "$i kill"
    done
 
  echo 'kill over ...'
fi

 

 

你可能感兴趣的:(linux,shell,linux,expect)