AnyEvent下的多个telnet客户端/命令

时间:2014-06-12 12:58:37

标签: perl telnet anyevent

如果我通过相同的telnet连接读取多个$_->{thand}->cmd($cmd)命令,我就会断开连接。

这表示多次调用ae_connect()。如何在AnyEvent下正确发送和获取数据?

use strict;
use warnings;
use Data::Dumper;

use AnyEvent::Socket;
use AnyEvent;
use Net::Telnet;

$| = 1;

my $arr = [
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1094 },
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1095 },
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1096 },
];

sub main_loop {

   my $cmd = "/ip firewall filter export";

   my $i=0;
   for (@$arr) {

     if (!$_->{thand}) {
       ae_connect($_);
       print("skip ", Dumper $_);
       next;
     }

     # print Dumper $_;
     $i++;
     my $s;
     $s = join "", $_->{thand}->cmd($cmd);
#     print "\n==1>$i  \n$s";
     $s = join "", $_->{thand}->cmd($cmd);
     $s = join "", $_->{thand}->cmd($cmd);

   }
   print "\n\n";
   #die @$arr*1 if $i;
}


sub ae_connect {
  my ($tc) = @_;

  print "=========== $tc->{Host} ============\n";
  tcp_connect $tc->{Host}, $tc->{Port} //23, sub {
    my ($fh) = @_ or return; # die "failed: $!";

    #
    my $t = new Net::Telnet->new(Fhopen => $fh) or return;

    eval { $t->login($tc->{username}, $tc->{passwd}) } or return;
    $t->timeout($tc->{Timeout});

    $tc->{thand} = $t;
    # $tc->{fh} = $fh;
  };

}

my $w = AnyEvent->timer(after => 0, interval => 1, cb => \&main_loop);

my $cv = AnyEvent->condvar;
$cv->recv;

1 个答案:

答案 0 :(得分:0)

我不认为AnyEvent和Net :: Telnet会一起工作。 AnyEvent是基于事件的,您有多个事件源,并将根据事件源对新数据执行操作,而Net :: Telnet只有一个文件句柄,并阻止等待目前所需的数据。

如果您需要并行多个Net :: Telnet连接,则需要使用多个进程或多个线程,或者您可能尝试使用Coroutines(例如Coro模块)。