Chinaunix首页 | 论坛 | 博客
  • 博客访问: 83493
  • 博文数量: 32
  • 博客积分: 1526
  • 博客等级: 上尉
  • 技术积分: 270
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-28 13:56
文章分类

全部博文(32)

文章存档

2012年(1)

2011年(15)

2010年(1)

2009年(15)

我的朋友
最近访客

分类: Python/Ruby

2011-12-04 18:50:25

工作中需要测试某个段的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;
}
阅读(2396) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~