1

我试图让一个期望脚本通过 ssh 进入远程系统,并获取远程命令的输出。我希望在本地提供该输出。例如,通过 ssh 进入系统并获取本地时间输出:

#!/usr/bin/expect --
set timeout 60
spawn ssh user@server.domain.com
expect {
timeout {puts "timed out after $timeout seconds"; exit}
"Password:"
}
send "SuperSecretPassword\r"
expect "user$ "
send "date\r"
expect "date"
expect "\r"
set buffer1 '$expect_out(buffer)'
expect "\r"
set buffer2 '$expect_out(buffer)'
send "exit\r"
expect eof
set buffer3 '$expect_out(buffer)'
exit
export VARIABLE $buffer1
export VARIABLE $buffer2
export VARIABLE $buffer3
echo "Okay, we are done expecting..."
echo "Buffer1: $buffer1"
echo "Buffer2: $buffer2"
echo "Buffer3: $buffer3"

自然,上述方法不起作用,实际上脚本执行在期望“退出”之后结束

4

2 回答 2

1
#!/usr/bin/expect --
log_user 0
set timeout 60
spawn ssh user@server.domain.com
expect {
timeout {puts "timed out after $timeout seconds"; exit}
"Password:"
}
send "mypassword\r"
expect "user$ "
send "date\r"
expect "date\r\n"
expect "*\r" { send_user "$expect_out(0,string)\n" }
close
exit
于 2013-05-22T14:26:02.467 回答
0

将数据从子进程(expect 脚本)传递到父进程(shell 脚本?)的方式是通过 stdio 通道:expect 脚本必须打印 expect_out 缓冲区,而 shell 脚本必须捕获期望输出并采取行动它以某种方式。

在之前exit,做类似的事情

puts "buffer1='$buffer1'"
puts "buffer2='$buffer2'"
puts "buffer3='$buffer3'"

您可能想要关闭所有其他期望输出。那是log_user 0……还有一些我想不起来的东西……Exploring Expect 这本书包含了所有精彩的细节。

shell脚本会做

expect_out=$(./program.exp)
while read line; do
    [[ $line == buffer[123]=* ]] && eval "$line"
done <<< "$expect_out"

或者也许只是

source <(./program.exp)

当然,expect 本身就是一种成熟且功能强大的语言 (Tcl),毫无疑问,它可以完成您需要做的所有本地工作,而无需费心调用期望和传回数据的 shell 脚本。

于 2013-05-16T00:17:39.953 回答