期望脚本:关闭ssh后执行操作

时间:2015-11-23 08:45:44

标签: bash expect

问题是保留变量并在bash中的expect脚本中关闭ssh后执行操作。

这是我到目前为止所得到的:

echo "Getting package name..."

getPackageName=$(expect -c '
exp_internal 1
log_user 1
global expect_out

# puts "Getting package name..."

spawn ssh -q -o StrictHostKeyChecking=no -o PreferredAuthentications=password -o PubkeyAuthentication=no -o RSAAuthentication=no -l user 10.20.30.40
sleep 1

expect {
    "*sword*" {
        send "12341234\r"
    }
    timeout {
        send_user "Error: timeout\n"
        exit 1
    }
}

expect {
    "*user@*>*" {
        # getting name of the latest modified file
        send "cd /export/home/user/Releases/build/1.3.32.0 && find * -type f -printf '"'"'%T@ %p\\n'"'"' | sort -n | tail -1 | cut -f2- -d\" \"\r"
    }
    timeout {
        send_user "Error: timeout\n"
        exit 1
    }
}

expect {
    "BUILD_MAIN*" {
        # assigning value to variable
        set result_lines [split $expect_out(0,string) \r\n]
        set package_filename [lindex $result_lines 0]
        puts "package_filename: $package_filename"
    }
    timeout {
        send_user "Error: timeout\n"
        exit 1
    }
}

expect "*#"
send "exit\r"

# here I need to perform some actions on local machine after ssh logout
expect "Connection*"
send "export LATEST_BUILD=$package_filename\r"
send_user "Message sent to user"

')

因此,在底部块中,我尝试在关闭ssh后在本地机器上设置环境变量(LATEST_BUILD),并且还粘贴一个变量(package_filename)的值,该值已在ssh会话期间定义。

这里的重点是我在输出中看到最后一条“发送给用户的消息”,但之前发送的“export LATEST_BUILD = 12345 \ r”显然不起作用。

1 个答案:

答案 0 :(得分:2)

#!/bin/bash

getPackageName=$(expect -c '

# A common prompt matcher
set prompt "%|>|#|\\\$ $"

# To suppress any other form of output generated by spawned process
log_user 0   

### Spawning ssh here ###
spawn ssh user@xxx.xx.xxx.xxx
expect "password"
send "welcome!2E\r"
expect -re $prompt  

# Your further code 

send "exit\r"
expect eof

##### The below segment is not needed ######
##### if your intention is to get only the 'package_filename' value #####
#    spawn bash
#    expect -re $prompt
#    send "export LATEST_BUILD=54.030\r"
#    expect -re $prompt
#    send "echo \$LATEST_BUILD\r"
#    expect -re $prompt
#    send "exit\r"
#    expect eof
#
##### The End ######


# Enabling logging now ...  
log_user 1
# Print only the value which you want to return
puts "$package_filename"
')

echo $getPackageName

eof用于标识文件结束事件,即关闭连接。

注意:导出的变量LATEST_BUILD仅适用于生成的bash会话。

更新:

log_user用于随时关闭/打开Expect生成的日志记录。

log_user 0; # Turn off logging
log_user 1; # Turn on logging

我希望你的唯一目的是获得package_filename。所以,我们甚至不需要产生bash shell。相反,只需最后打印该值,从而使其可用于父bash脚本。