您的位置:首页 > 编程语言

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

2008-01-23 16:03 176 查看
线程是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 );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: