我正在尝试将一个expect脚本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"
当然,上面的方法不起作用,实际上脚本执行在期望“退出”之后结束
答案 0 :(得分: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
答案 1 :(得分:0)
将数据从子进程(期望脚本)传递到父进程(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脚本