2014-03-27 26 views
1

提供的數據循環我使用下面的lib Net::SSH2通過網:: SSH2

我可以連接到我的設備和得到的輸出在大多數情況下確定。下面是相關的代碼:

sub logIntoDevice 
{ 
    my $self = shift; 
    my ($ssh2) = @_; 

    if(! $ssh2->connect($self->deviceIP)) 
    { 
    say "Failed to connect to device:",$self->deviceIP; 
    $ssh2->disconnect(); 
    exit 0; 
    } 
    if(! $ssh2->auth_password($self->usr, $self->pass)) 
    { 
    say "Authentication Fail to ",$self->deviceIP; 
    $ssh2->disconnect(); 
    exit 0; 
    } 
    my $channel = $ssh2->channel(); 
    $channel->blocking(0); 
    $channel->shell(); 
    return $channel; 
} 

sub sendCmd 
{ 
    my $self = shift; 
    my ($cmd,$channel) = @_; 
    my @cmdOutput; 

    print $channel "$cmd\n"; 
    while (<$channel>) 
    { 
    chomp $_; 
    push(@cmdOutput, $_); 
    } 
    return @cmdOutput; 
} 

所以下面是我發送到子的cmd。它們工作正常,輸出寫入文件OK。

$self->writeToFile($fileName,$self->sendCmd("show clock",$channel)); 
$self->writeToFile($fileName,$self->sendCmd("\n",$channel)); 
$self->writeToFile($fileName,$self->sendCmd("dir",$channel)); 

與當我發送以下CMD除外:

$self->writeToFile($fileName,$self->sendCmd("sh run",$channel)); 

使用膩子設備上的CMD的輸出爲:

sh run 
Building configuration... 


Current configuration : 16575 bytes 
! 
! 
!Last configuration change at 16:37:19 CET+1 Sat Mar 15 2014 
..... 

但在日誌文件中的所有你看到的是

sh run 
Building configuration... 

所以問題是Building configuration輸出後的空行使while (<$channel>)認爲它是輸出的結尾。

我的問題是我無法找到一種方式來循環數據,而不使用While循環。

UPDATE

好想出這個解決方案,但似乎很笨重。必須有一個更好的方式,如果這樣做

sub sendCmd 
{ 
my $self = shift; 
my ($cmd,$channel) = @_; 
my @cmdOutput; 
my $currPrompt; 

#get prompt. i am sure there is a better way!!! just cant figure it out 
print $channel "\n"; 
while (<$channel>) 
{ 
    $currPrompt = $_; 
} 
print $channel "$cmd\n"; 
while(42) 
{ 
    my $inerOutput; 
    while (<$channel>) 
    { 
    chomp $_; 
    $inerOutput = $_; 
    push(@cmdOutput, $_); 
    } 
    if($inerOutput ne $currPrompt) 
    { 
    sleep(7); 
    } 
    else 
    { 
    last; 
    } 
} 
return @cmdOutput; 

}

回答

0

我不認爲你的問題是空白行。最有可能的問題是,您正在使用非阻塞模式,並且設備執行命令需要時間。因此,在讀取「Building configuration ...」之後,您將得到一個空行(或一個undef),因爲沒有產生額外的輸出。

我會用超時的Net :: SSH2的poll方法,它會讓你知道什麼時候有東西要讀。如果「sh run」比你發佈的其他命令花費的時間長得多,你的sendCmd方法需要知道這一點,並且在決定沒有更多的輸出來臨之前允許有更多的時間通過。

或者,您可以(如使用時的習慣,例如Net :: Telnet)等待更多輸出,直到看到提示,無論提示是否有問題的設備 ,然後您將知道該命令已完成其執行。

+0

你能我如何能循環雖然<$channel>提供進一步的解釋。我可以得到提示並匹配它退出,但不知道如何通過<$channel>無限循環直到提示匹配。 – alexis