capture expect ssh output to variable

16.4k views Asked by At

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

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?

1

There are 1 answers

0
Dinesh On BEST ANSWER

A generic idea can be something like as below.

  1. spawn the ssh session
  2. make proper login
  3. Send each commands with send
  4. Wait for desired output with 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

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 -re $prompt; #Using regex to match the pattern`