bash 捕获期望 ssh 输出到变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27002622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:48:53  来源:igfitidea点击:

capture expect ssh output to variable

bashsshexpectcapture

提问by auahmed

Hey am new to bash scripts and was wondering how would I capture the output of the sshcommand into a bash variable? I looked around and cant seem to get it right. I have tried puts $expect_out(buffer)but when echoit says variable does not exist

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

I know the response should be just one line and if I want to save that into a variable responseand then echoit how would I do that?

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

采纳答案by Dinesh

A generic idea can be something like as below.

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

  1. spawnthe ssh session
  2. make proper login
  3. Send each commands with send
  4. Wait for desired output with expect
  1. spawnssh 会话
  2. 正确登录
  3. 发送每个命令 send
  4. 等待所需的输出 expect

Example:

例子:

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.

The word to wait for after executing the command can vary based on your system. It can be #or $or >or :; So, make sure you are giving the correct one. Or, you can provide a generalized pattern for the prompt as such

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

set prompt "#|>|:|\$"; # We escaped the `$` symbol with backslash to match literal '$'

While using the expectafter sending the commands, it can be used as

在使用expect发送命令后,它可以用作

expect -re $prompt; #Using regex to match the pattern`