in reply to An efficient way to do this?
#!/usr/bin/perl use warnings; use strict; use Net::Ping; use Net::Netmask; use Getopt::Long; use Pod::Usage; use Log::Log4perl; my $conf = q( log4perl.category.Find_M = INFO, ScreenAppender log4perl.appender.ScreenAppender = Log::Log4perl::Appen +der::Screen log4perl.appender.ScreenAppender.stderr = 1 log4perl.appender.ScreenAppender.layout = PatternLayout log4perl.appender.ScreenAppender.layout.ConversionPattern=%m%n log4perl.appender.ScreenAppender.Threshold = DEBUG ); Log::Log4perl::init(\$conf); my $log = Log::Log4perl::->get_logger(q(Find_M)); my $help = undef; my $netblock = undef; my $timeout = 5; GetOptions( "help|?" => \$help, "timeout=i" => \$timeout, "netblock=s" => \$netblock ) or pod2usage(2); pod2usage(1) if $help; pod2usage(q{Missing argument 'netblock'.}) if !$netblock; $log->debug(qq{netblock:$netblock}); ################################################################## sub create_generator { ################################################################## my @netmasks; for my $block (@_) { $log->debug(qq{block $block}); push @netmasks, Net::Netmask->new($block); } my $nth = 1; return sub { return unless @netmasks; my $next_ip = $netmasks[0]->nth($nth++); if ($next_ip eq $netmasks[0]->last()) { shift @netmasks; $nth = 1; } $log->debug(qq{returning next_ip $next_ip}); return $next_ip; } } # ------ main my $next_address = create_generator($netblock); my $p = Net::Ping->new(); while (my $address = $next_address->()) { if ($p->ping($address, $timeout)) { $log->info(qq{host $address is up.}); } else { $log->debug(qq{host $address did not respond.}); } } $p->close(); __END__ =pod =head1 NAME find_machines.pl - find responding machines in network subnet. =head1 SYNOPSIS find_machines.pl --netblock "192.168.2.0/24" =head1 AUTHOR Perl Hack #26 in book I<perl hacks>. =head SEE ALSO Net::Netmask =cut
$ perl find_machines.pl --netblock "192.168.2.0/24" host 192.168.2.2 is up. host 192.168.2.3 is up. host 192.168.2.6 is up. host 192.168.2.10 is up. host 192.168.2.19 is up.
|
|---|