【perl】ping一个或者多个IP段地址

2415阅读 0评论2011-12-04 正愚
分类:Python/Ruby

工作中需要测试某个段的IP地址是否能够正常ping,写了一个简单脚本。用法如下:

Usage:
autoping.pl -f file
autoping.pl -a address -m netmask
Options:
-f file contains ip and netmask, each line like '192.168.1.0\24'
-a network address, like '192.168.1.0'
-m netmask number, like '24'
-v display the version
-h Help!

============================================================================================

#!/usr/bin/perl -w

use strict;
use Net::IP;
use Getopt::Long;

use constant USAGE =>
"Usage:\n".
"\t$0 -f file\n".
"\t$0 -a address -m netmask\n".
"\t[-f file] [-a address] [-n netmask] [-v version] [-h help]\n".
"Options:\n".
"\t-f file contains ip and netmask, each line like '192.168.1.0\\24'\n".
"\t-a network address, like '192.168.1.0'\n".
"\t-m netmask number, like '24'\n".
"\t-v display the version\n".
"\t-h Help!\n";
use constant VERSION => "Version: 1.0.0\n";

my $address;
my $mask;
my $parameter;
my $help;
my $version;
my $ipfile = "ipfile.txt";
my $ping = "/bin/ping";
my @iplist;
my $file;
my @record;

GetOptions(
    "file=s"   => \$file,
    "address=s"   => \$address,
    "mask=i"        => \$mask,
    "help!"         => \$help,
    "version!"      => \$version,
) or die USAGE;

die USAGE if ($help);
die VERSION if ($version);

if (($address) && ($mask)){
$parameter = "$address"."/"."$mask";
&process;
}
elsif($file){
open (IN,"$file" || die $!);
while(){
chomp;
s/\s+//g;
push @record,$_;
}
close(IN);
foreach (@record){
$parameter = $_;
&process;
$#iplist = -1;
}
}
else {
die USAGE;
}

sub process {
unlink $ipfile;
open (OUT,"> $ipfile" || die $!);
select OUT;
my $ip = new Net::IP ($parameter) or die;
do {
print $ip -> ip(),"\n";
} while(++$ip);

close (OUT);
select STDOUT;
open (IN,"< $ipfile" || die $!);
while(){
chomp;
push @iplist,$_;
}
close(IN);
my @index = (1 .. $#iplist-1);
foreach (@index) {
if (`$ping -c 5 $iplist[$_]` =~ /100% packet loss/){
print "$iplist[$_]\n";
}
}
$#index = -1;
}
上一篇:【perl】清空一个数组
下一篇:Windows系统自动登录