gpt4 book ai didi

Perl 脚本不能 fork 超过 10 次

转载 作者:行者123 更新时间:2023-12-01 12:50:16 25 4
gpt4 key购买 nike

我的 perl 代码不允许超过 10 个 fork。对于以下 perl 代码,每当我在读入脚本的机器列表中使用超过 10 台机器时,perl 脚本只会为 10 台机器派生 10 个进程,其余的会因错误而死:

SSHProcessError SSH 进程已终止。在 serverLogin.pl 44它在 $ssh->waitfor('The authenticity of host*',15); 处死掉。

PERL 脚本:

#!/usr/bin/perl -w

use Net::SSH::Expect;
use Term::ReadKey;


print "please enter filename:\n";
$filename = ReadLine;
chomp $filename;

print "please enter user ID:\n";
$userID = ReadLine;
chomp $userID;

print "please enter password:\n";
ReadMode 'noecho';
$passwordforuser = ReadLine 0;
chomp $passwordforuser;
ReadMode 'normal';

open READFILE,"<","$filename" or die "Could not open file listofmachines\n";

my @listofmachines = <READFILE>;

foreach $machine (@listofmachines)
{
my $pid=fork();

if ($pid){
push(@childprocs,$pid);
}
elsif ( $pid == 0 ) {
my $ssh = Net::SSH::Expect->new (
host => "$machine",
user => "$userID",
password=> "$passwordforuser",
timeout => 25,
raw_pty => 1,
);

my $login_output = $ssh->run_ssh or die "Could not launch SSH\n";

$ssh->waitfor('The authenticity of host*',15);

#print "This output for machine $machine\n";

$ssh->send("yes");
$ssh->waitfor('password: ', 15);
$ssh->send("$passwordforuser");
$ssh->waitfor('$ ', 10);
my @commresult=$ssh->exec("uptime");

print $login_output;
print @commresult;

exit 0;
}
else {
die "Could not Fork()\n";
}
}

foreach(@childprocs){
waitpid($_, 0)
}

请帮忙。谢谢,nblu。

最佳答案

您的脚本使用 Net::OpenSSH::Parallel而不是 Net::SSH::Expect。

同时连接的数量限制为 10,以克服脚本中发生的任何资源耗尽问题(可能是 PTY):

#!/usr/bin/perl -w

use Net::OpenSSH::Parallel;
use Term::ReadKey;

print "please enter filename:\n";
$filename = ReadLine;
chomp $filename;

print "please enter user ID:\n";
$userID = ReadLine;
chomp $userID;

print "please enter password:\n";
ReadMode 'noecho';
$passwordforuser = ReadLine 0;
chomp $passwordforuser;
ReadMode 'normal';

open READFILE,"<","$filename" or die "Could not open file listofmachines\n";

my @listofmachines = <READFILE>;
chomp @listofmachines;

my $pssh = Net::OpenSSH::Parallel->new(connections => 10);
$pssh->add_host($_,
user => $userID, password => $passwordforuser,
master_opts => [-o => 'StrictHostKeyChecking=no'])
for @listofmachines;

sub do_ssh_task {
my ($host, $ssh) = @_;
my $output = $ssh->capture('uptime');
print "$host: $output";
}

$pssh->all(parsub => \&do_ssh_task);
$pssh->run;

for my $host (@listofmachines) {
if (my $error = $pssh->get_error($host)) {
print STDERR "remote task failed for host $host: $error\n";
}
}

关于Perl 脚本不能 fork 超过 10 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com