0

I have to capture output of the send command when using Perl Expect module.

I know that in shell or Tcl I can use puts $expect_out(buffer); to capture the previously run command.

How can I do the same thing in Perl?

I am sending below command on remote machine:

$expect->send("stats\n");

I need to capture the stats output in some variable.

pynexj
  • 19,215
  • 5
  • 38
  • 56
Bhushan Patil
  • 59
  • 1
  • 12
  • 1
    Did you check the Expect module documentation: http://search.cpan.org/~szabgab/Expect-1.32/lib/Expect.pm#I_just_want_to_read_the_output_of_a_process_without_expect%28%29ing_anything._How_can_I_do_this? – jira Jun 07 '16 at 05:53
  • Also, looks like duplicate of http://stackoverflow.com/questions/26908683/get-the-output-of-a-command-executed-via-self-send-on-a-remote-host-in-perl?rq=1 – jira Jun 07 '16 at 05:58
  • Yes, checked but no help..!! – Bhushan Patil Jun 07 '16 at 06:12
  • This is not duplicate of http://stackoverflow.com/questions/26908683/get-the-output-of-a-command-executed-via-self-send-on-a-remote-host-in-perl?rq=1, this is different question. – Bhushan Patil Jun 07 '16 at 06:13
  • Don't you `expect` after `send` to receive the answer? – zdim Jun 07 '16 at 06:54

1 Answers1

1

First of all you have to know how the last line of your CLI looks like after the output of your requested data. The Expect cann search for a certain Pattern within your defined timeout. If it found sth. you can capture everything since your $expect->send($command) with the $exp-before()-command. Or if you wish to capture everything after your command just use $expect->after() without checking for a special symbol.

Let me give you an example:

$expect->send("$command\n");
#mask the pipe-symbol for later use. Expect expects a valid regex
$command =~ s/\|/\\\|/;
#if a huge amount of data is requested you have to avoid the timeout
$expect->restart_timeout_upon_receive(1);
if(!$expect->expect($timeout, [$command])){ #timeout
   die: "Timeout at $command";
}else{
   #command found, no timeout
   $expect->after();
   $expect->restart_timeout_upon_receive(1);
   if(!expect->expect($timeout,["#"])){
     die "Timeout at $command";
   } else{
      $data = $expect->before(); #fetch everything before the last expect() call
   }
}
   return $data;

So you have to fire your command, then expect your command been fired. After this you can fetch everything till your command prompt, in my case it's indicated by the #. The rows between your command and the last $expect->expect($timeout,["#"] will be stored in $data as a single string. After that you can process this String.

I hope I could help you a bit further. ;)

Otterbein
  • 544
  • 3
  • 12