【发布时间】:2016-11-29 21:05:08
【问题描述】:
我正在使用以下库Net::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));
设备上使用putty的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 循环来循环数据的方法。
更新
好的,想出这个解决方案,但看起来很笨拙。如果这样做一定是更好的方法
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;
}
【问题讨论】: