Если вы спрашиваете, о чем я думаю, просто запустите каждую команду $chan->exec
в отдельном потоке (Предупреждение: не проверено):
use warnings;
use strict;
use NET::SSH2;
use threads;
use threads::shared;
#We'll be making a Net::SSH2 object in each thread,
#so these parameters will need to be shared between the threads.
my $host :shared = "switchA"; # use the ip host to connect
my $user :shared = "XXX"; # your account
my $pass :shared= "XXXX"; # your password
#NOTE: The shell use (via $ssh2 and $chan) has been passed
#to the subroutines foo and bar.
#Create two threads,
#one which will perform the subroutine foo,
#and the other which will perform the subroutine bar.
my $thread1=threads->create(\&foo);
my $thread2=threads->create(\&bar);
#Wait for the threads to finish.
$thread1->join;
$thread2->join;
sub foo
{
my $ssh2 = Net::SSH2->new();
$ssh2->debug(0);
$ssh2->connect($host) or die "Unable to connect host $@ \n";
$ssh2->auth_password($user,$pass);
my $chan = $ssh2->channel();
$chan->exec('sh int desc');
my $buflen = 3000;
my $buf1 = '0' x $buflen;
$chan->read($buf1, $buflen);
open(my $write,">","/output/file/foo") or die $!;
print $write "CMD1:\n", $buf1,"\n";
close($write);
}
sub bar
{
my $ssh2 = Net::SSH2->new();
$ssh2->debug(0);
$ssh2->connect($host) or die "Unable to connect host $@ \n";
$ssh2->auth_password($user,$pass);
my $chan = $ssh2->channel();
$chan->exec('sh ver');
my $buflen2 = 3000;
my $buf2 = '0' x $buflen2;
$chan->read($buf2, $buflen2);
open(my $write,">","/output/file/bar") or die $!;
print $write "CMD2:\n", $buf2,"\n";
close($write);
}
Посмотрите на perldoc perlthrtut
, чтобы узнать больше о темах.
Отредактировано, чтобы добавить: Недостаток подхода, описанного выше, заключается в том, что вы запускаете два SSH-соединения (по одному на поток) вместо одного. Здесь можно добавить дополнительный уровень сложности, запустив одно соединение вне потоков (и имея $ssh2
в качестве переменной shared
), а затем используя семафор (или даже lock
), чтобы убедиться, что удаленный терминал не смущен командой одного потока, пытающейся наступить на команду другого потока.