0

Expect使用 Perl模块时,我必须捕获发送命令的输出。

我知道在 shell 或 Tcl 中我可以puts $expect_out(buffer);用来捕获以前运行的命令。

我怎样才能在 Perl 中做同样的事情?

我在远程机器上发送以下命令:

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

我需要stats在某个变量中捕获输出。

4

1 回答 1

1

首先,您必须知道您的 CLI 的最后一行在您请求的数据输出后的样子。cannExpect在您定义的超时时间内搜索特定模式。如果它找到了。您可以使用 - 命令捕获自您以来的所有$expect->send($command)内容$exp-before()。或者,如果您希望在命令后捕获所有内容,只需使用$expect->after()而不检查特殊符号。

让我给你举个例子:

$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;

所以你必须触发你的命令,然后期望你的命令被触发。在此之后,您可以获取所有内容,直到您的命令提示符,在我的情况下,它由#. 您的命令和最后一行之间的行将$expect->expect($timeout,["#"]作为单个字符串存储在 $data 中。之后,您可以处理此字符串。

我希望我能帮助你更进一步。;)

于 2016-06-07T11:03:02.697 回答