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
capture expect ssh output to variable
提问by auahmed
Hey am new to bash scripts and was wondering how would I capture the output of the ssh
command into a bash variable? I looked around and cant seem to get it right. I have tried puts $expect_out(buffer)
but when echo
it 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 response
and then echo
it how would I do that?
我知道响应应该只是一行,如果我想将它保存到一个变量中response
,然后echo
我该怎么做?
采纳答案by Dinesh
A generic idea can be something like as below.
一个通用的想法可能如下所示。
spawn
the ssh session- make proper login
- Send each commands with
send
- Wait for desired output with
expect
spawn
ssh 会话- 正确登录
- 发送每个命令
send
- 等待所需的输出
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 expect
after sending the commands, it can be used as
在使用expect
发送命令后,它可以用作
expect -re $prompt; #Using regex to match the pattern`