Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture expect ssh output to variable

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?

like image 742
auahmed Avatar asked Sep 29 '22 09:09

auahmed


1 Answers

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`
like image 90
Dinesh Avatar answered Oct 30 '22 03:10

Dinesh