shell远程交互脚本的使用(expect)

使用场景服务器A需要远程调用服务器B上的脚本,由于脚本需要交互的执行,所以需要expect,可以预定一些参数用户交互执行,具体实例如下:
直接执行sh A.sh即可,远程机器B的脚本B.sh就会运行

调用脚本A.sh

#!/bin/bash
currentdir=$(cd `dirname $0`;pwd)
${currentdir}/expect.sh "192.168.0.108" "root" "1" "20" "22" "/home/mm/expect"  >> ${currentdir}/expect.log 2>&1
echo $?
exit $?
  • expect.sh
#!/usr/bin/expect
set REMOTEIP [lindex $argv 0]
set USERNAME [lindex $argv 1]
set PASS_WD [lindex $argv 2]
set TIME_OUT [lindex $argv 3]
set SSH_PORT [lindex $argv 4]
set WORK_PATH [lindex $argv 5]

 ##设置超时时间
 if { $TIME_OUT > 0 } {
    set timeout ${TIME_OUT}
 } elseif { "$TIME_OUT" == "-1" } {
    set timeout -1  
 } else {
    set timeout 3000
 }

set command_ssh_port ${SSH_PORT}
set pass ${PASS_WD}

   spawn ssh-keygen -R ${REMOTEIP}B
   spawn ssh  -p ${command_ssh_port}  "$USERNAME@$REMOTEIP" "sudo sh ${WORK_PATH}/B.sh"
   expect {
			-nocase -re ".*yes/no.*" {
					exp_send "yes\n"
					exp_continue
			}
			-nocase -re ".*assword.*" {
					exp_send "${pass}\n"
			}
			-nocase -re ".*Connection refused.*" {
					send_error "ERROR:$REMOTEIP:Connection refused;\n"
					exit 12;
			}
	}
   expect {
			-nocase -re ".*No route.*" {
					send_error "ERROR:$REMOTEIP:No route;\n"
					exit 12;
			}
			timeout {
					send_error "ERROR:$REMOTEIP:Connect to server timeout($timeout s).\n"
					exit 13
			}
	eof
   }

##等待执行结果
catch wait exitcode
set real_exit_code [lindex $exitcode 3]
if { "$real_exit_code" != "0" } {
      send_error "\nERROR:$REMOTEIP:unkown error.\n"
 }
exit [lindex $exitcode 3]

远程被调用较脚本B.sh

#!/bin/sh
currentdir=$(cd `dirname $0`;pwd)
echo begin >> $currentdir/test.log
sleep 5
echo $? >> $currentdir/test.log
echo end >> $currentdir/test.log
exit 1
posted @ 2021-11-20 19:26  桂花载酒少年游O  阅读(406)  评论(0编辑  收藏  举报