提供的數據循環我使用下面的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;
}
你能我如何能循環雖然<$channel>提供進一步的解釋。我可以得到提示並匹配它退出,但不知道如何通過<$channel>無限循環直到提示匹配。 – alexis