当使用Perl Expect
模块时,我必须捕获send命令的输出。如何捕获使用Expect发送的命令的结果
我知道在shell或Tcl中,我可以使用puts $expect_out(buffer);
来捕获以前运行的命令。
我该怎么在Perl中做同样的事情?
我远程机器上发送以下命令:
$expect->send("stats\n");
我需要捕获在一些变量的stats
输出。
当使用Perl Expect
模块时,我必须捕获send命令的输出。如何捕获使用Expect发送的命令的结果
我知道在shell或Tcl中,我可以使用puts $expect_out(buffer);
来捕获以前运行的命令。
我该怎么在Perl中做同样的事情?
我远程机器上发送以下命令:
$expect->send("stats\n");
我需要捕获在一些变量的stats
输出。
首先,您必须知道在输出所请求的数据后,CLI的最后一行的样子。 Expect
cann可以在您定义的超时时间内搜索特定的模式。如果它发现了某事您可以捕获自$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中。之后,你可以处理这个字符串。
我希望我可以帮你一点。 ;)
您是否检查了Expect模块文档: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
此外,看起来像重复的http://stackoverflow.com/questions/26908683/get-the-output-of-a-command-executed-via-self-send-on-a-remote-host-in-perl ?rq = 1 – jira
是的,检查,但没有帮助..! –