捕获期望ssh输出到变量

aua*_*med 5 ssh bash expect capture

嘿,我是bash脚本的新手,想知道如何将ssh命令的输出捕获到bash变量中?我环顾四周,似乎无法正确行事.我尝试过put $expect_out(buffer)但是当echo它说变量不存在时

我知道响应应该只是一行,如果我想将它保存到变量中response,那么echo我该怎么做?

Din*_*esh 4

一个通用的想法可以如下所示。

  1. spawnssh 会话
  2. 进行正确的登录
  3. 发送每个命令send
  4. 等待所需的输出expect

例子:

spawn ssh $user@$domain
expect "password" { send "$pwd\r"}
expect "#"; # This '#' is nothing but the terminal prompt
send "$cmd\r"
expect "#"
puts $expect_out(buffer);  #Will print the output of the 'cmd' output now.
Run Code Online (Sandbox Code Playgroud)

执行命令后等待的字可能因您的系统而异。它可以是#$>; :因此,请确保您提供的是正确的信息。或者,您可以为提示提供通用模式

set prompt "#|>|:|\\\$"; # We escaped the `$` symbol with backslash to match literal '$'
Run Code Online (Sandbox Code Playgroud)

发送命令后使用时expect,可用作

expect -re $prompt; #Using regex to match the pattern`
Run Code Online (Sandbox Code Playgroud)