2016-06-07 45 views
0

當使用Perl Expect模塊時,我必須捕獲send命令的輸出。如何捕獲使用Expect發送的命令的結果

我知道在shell或Tcl中,我可以使用puts $expect_out(buffer);來捕獲以前運行的命令。

我該怎麼在Perl中做同樣的事情?

我遠程機器上發送以下命令:

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

我需要捕獲在一些變量的stats輸出。

+1

您是否檢查了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

+0

此外,看起來像重複的http://stackoverflow.com/questions/26908683/get-the-output-of-a-command-executed-via-self-send-on-a-remote-host-in-perl ?rq = 1 – jira

+0

是的,檢查,但沒有幫助..! –

回答

0

首先,您必須知道在輸出所請求的數據後,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中。之後,你可以處理這個字符串。

我希望我可以幫你一點。 ;)

相關問題