perl连接SSH的代码,RH AS3,Perl 5.8时使用的

线程是10个,写在代码里面了,没有作为参数。

#!/usr/bin/perl

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

local $SIG{ALRM} = sub { die "timeout/n"; };

sub Usage
{
        print "This script used to execute command on remote server,code by xingguo/n";
        print "GetPkgVer.pl  <HostFile>  <TimeOut>   <ResultFile>/n";

        exit 0;
}

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

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

my $user = "name";
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 = "last | grep hacker";

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 ExecCmd
{
        my $host = shift;
        chop( $host );

        my $current_host = $host;
        print "testing $host.../n";

        my $output;

        eval
        {
                alarm($time_out);

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

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

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

                if( $output ne "" )
                {
                        print ResultHandle "$host:/n$output/n";
                        print "$host:/n$output/n";
                }
                alarm(0);
        };
        if( $@ =~ /timeout/ )
        {
                print "Connect to $current_host time out./n";
        }
}

while( my $host = <HostsHandle> )
{
        my $total = threads -> list( );

        while( 1 )
        {
                if( $total >= $max_thread )
                {
                        $total = threads -> list( );

                        #print "Now Count: $total/n";

                        foreach my $join_thread ( threads -> list(threads::joinable) )
                        {
                                #print "Try to join ".$join_thread -> tid( )."/n";
                                $join_thread -> join( );

                                $total --;
                        }
                        sleep 1;
                }
                else
                {
                        last;
                }
        }

        my $work_thread = threads -> new( /&ExecCmd, $host );
}

foreach my $join_thread ( threads->list(threads::all) )
{
        $join_thread -> join( );
}

print "All Done!!/n";

close( ResultHandle );
close( HostsHandle ); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值