【问题标题】:Looping through data provided by Net::SSH2循环通过 Net::SSH2 提供的数据
【发布时间】: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 (&lt;$channel&gt;) 认为它是输出的结尾。

我的问题是我无法找到一种不使用 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;

}

【问题讨论】:

    标签: perl net-ssh


    【解决方案1】:

    我不认为您的问题是空行。最有可能的问题是您使用的是非阻塞模式,并且设备执行命令需要时间。因此,在读取“正在构建配置...”后,您会得到一个空行(或 undef),因为还没有产生额外的输出。

    我会使用 Net::SSH2 的 poll 方法并设置一个超时时间,这会让你知道什么时候需要阅读。如果“sh run”比您发出的其他命令花费的时间要长得多,那么您的 sendCmd 方法需要意识到这一点,并在它决定不再有输出出现之前留出更多时间。

    或者,您可以(如使用 Net::Telnet 时的习惯)等待更多输出,直到您看到提示,无论提示是针对相关设备的提示, 然后你就会知道命令已经执行完毕了。

    【讨论】:

    • 您能否进一步解释我如何通过 进行循环。我可以得到提示并将其匹配以退出,但不确定如何无限期循环 直到提示匹配。
    【解决方案2】:

    Net::SSH2->polllibss2_poll 弃用而弃用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多