我有一个Perl脚本,它使用SSH登录文本文档中的服务器,或者选择要使用的脚本,并执行set命令。
此脚本需要很长时间才能通过70列表,有时它也会随机停止。它说它仍在执行脚本,但它停止发送命令。
我需要一种方法来防止它冻结,并且还能更快地运行
#!/usr/bin/perl
use Net::SSH2;
open(fh,'<','servers.txt');
@newarray;
while (<fh>){
@array = split(':',$_);
push(@newarray,@array);
}
$a=0;
$b=1;
$c=2;
while ($c <= scalar(@newarray)){
$ssh = Net::SSH2->new();
if ($ssh->connect($newarray[$c])) {
if ($ssh->auth_password($newarray[$a],$newarray[$b])) {
$channel = $ssh->channel();
$channel->exec('cd /tmp && perl p.pl');
$channel->close;
print "Command sent to --> ".$newarray[$c]."\n";
} else {
print "Could not authenticate to host $newarray[$c]\n";
}
} else {
print "Could not connect to host $newarray[$c]\n";
}
$a += 3;
$b += 3;
$c += 3;
}
答案 0 :(得分:1)
您可以使用ForkManager
轻松地将任务并行化#!/usr/bin/perl
use Net::SSH2;
use Parallel::ForkManager;
#######################
# Written by Iyzan #
#######################
open(fh,'<','servers.txt');
@newarray;
while (<fh>){
@array = split(':',$_);
push(@newarray,@array);
}
# make 10 workers
my $pm = new Parallel::ForkManager(10);
for (my $i=0; $i < scalar(@newarray); $i+=3) {
# fork a worker
$pm->start and next;
$a = $i;
$b = $i+1;
$c = $i+2;
$ssh = Net::SSH2->new();
if ($ssh->connect($newarray[$c])) {
if ($ssh->auth_password($newarray[$a],$newarray[$b])) {
$channel = $ssh->channel();
$channel->exec('cd /tmp && perl p.pl');
$channel->close;
print "Command sent to --> ".$newarray[$c]."\n";
} else {
print "Could not authenticate to host $newarray[$c]\n";
}
} else {
print "Could not connect to host $newarray[$c]\n";
}
# exit worker
$pm->finish;
}
$pm->wait_all_children;