Combinando con threads

El siguiente ejemplo muestra como dos threads generan conexiones ssh con dos máquinas ejecutando el mismo comando en ambas.

#!/usr/bin/perl -w
use strict;
use Net::SSH::Perl;
use threads;
use Data::Dumper;

our $numthreads;

my (@pass, @host);

my $user = 'XXXX';

$pass[0] = 'XXXX'; $host[0] = 'XXXX';

$pass[1] = 'XXXX.'; $host[1] = 'XXXX';

sub par {
  my $nt = shift();
  my $task = shift;
  my @t; # array of tasks
  my $i;
  my @results;

  for($i=1; $i < $nt; $i++) {
    $t[$i] = threads->new($task, @_);
  }
  @{$results[0]} = $task->( @_);
  for($i=1; $i < $nt; $i++) {
    @{$results[$i]} = $t[$i]->join();
  }
  @results;
}

sub ssh {
  my $cmd = shift();
  my $id = threads->self()->tid();
  my $pass = $pass[$id];
  my $host = $host[$id];
  my ($stdout, $stderr, $exit) = ('', '', '');
  my $ssh = Net::SSH::Perl->new($host);
  $ssh->login($user, $pass);
  [ $ssh->cmd($cmd) ];
}

$numthreads = (shift || 2);
my @results = par($numthreads, \&ssh, 'pwd');

print Dumper(\@results);
Ejecución:
$ ./example2.pl
Argument "ssh-rsa" isn't numeric in numeric eq (==) at /usr/local/share/perl/5.8.4/Net/SSH/Perl/Key/RSA1.pm line 94, <FH> line 6.
Argument "ssh-dss" isn't numeric in numeric eq (==) at /usr/local/share/perl/5.8.4/Net/SSH/Perl/Key/RSA1.pm line 94, <FH> line 20.
$VAR1 = [ [ [ '/user1/uni/ull/casiano ', 'MANPATH: Undefined variable.  ', 0 ] ],
          [ [ '/home/casiano ', undef, 0 ] ]
        ];

Casiano Rodríguez León
Licencia de Creative Commons
Programación Distribuida y Mejora del Rendimiento
por Casiano Rodríguez León is licensed under a Creative Commons Reconocimiento 3.0 Unported License.

Permissions beyond the scope of this license may be available at http://campusvirtual.ull.es/ocw/course/view.php?id=44.
2012-06-19