An Example of Perl Multi-thread 2

该脚本通过多线程方式批量从远程服务器获取指定软件包的版本信息,并将结果记录到文件中。支持超时设置及错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/perl

use threads;    
use Net::SSH::Perl;
use strict;

my $current_host;

local $SIG = sub { print "connect $current_host time out/n";return; };

sub Usage
{
        print "This script used to get the package's version from remote server,code by xingguo/n";
        print "GetPkgVer.pl     <HostFile>      <Name>   <TimeOut>       <ResultFile>/n";

        exit 0;
}

if( @ARGV != 4 )
{
        Usage( );
}

my $hosts_file = $ARGV[0];
my $package = $ARGV[1];
my $time_out = $ARGV[2];
my $result_file = $ARGV[3];

my $user = "user";
my $pass = "password";

if( -e $result_file )
{
        print "Result file exists,please change another one/n";
        exit 0;
}

my $max_thread = 10;
my @thread_array;

my $cmd = "yinst list $package";

system( "touch $result_file" );

open( ResultHandle, ">> $result_file" ) || die "Open result file error.../n";

open( HostsHandle, "< $hosts_file" ) || die "Open hosts list error.../n";

sub GetVersion
{
        my $host = shift;
        chop( $host );

        $current_host = $host;
        print "/nDebug:Try to get package version from $host.../n";

        my $output;

        eval
        {
                alarm $time_out;

                my $ssh = Net::SSH::Perl->new( $host );

                $ssh->login($user, $pass);

                my( $output ) = $ssh->cmd($cmd);

                alarm 0;

                if( $output =~ /$package/ )
                {
                        print ResultHandle "$host/t$output/n";
                        print "$host/t$output/n";
                }
        };
}

my $current_thread = 0;
while( my $host = <HostsHandle> )
{
        if( $current_thread >= $max_thread )
        {
                foreach my $thread( @thread_array )
                {
                        $thread -> join( );
                }

                $current_thread = 0;
        }

        $thread_array[$current_thread] = threads -> new( /&GetVersion, $host );
        $current_thread ++;
}

close( ResultHandle );
close( HostsHandle );

 

from: http://icylife.net/yunshu/show.php?id=346

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值