去Ping的路更快

  • 本文关键字:Ping bash ping
  • 更新时间 :
  • 英文 :


我需要对254个主机(例如X.X.X.1-X.X.X.254(执行ping扫描,并将结果输出到一个文件中以供以后操作。目前我有一个bash脚本可以为我做这件事,然而,它非常慢。有没有办法加快速度?如果可能的话,我希望能够使用ping命令并使用bash作为脚本语言。

我的脚本如下:

#!/bin/bash
for i in {1..254}
do
ping -c 1 X.X.X.$i >> results.txt
done

注意:我实际上没有字符"X"。X.X'在我的代码中,相反,我有实际的IP地址。

作为Nagios监控管理员,我在当天写了这个Perl脚本来验证主机是否在ping。有时,我需要检查数百台主机,我也需要更快的响应时间。

当您使用Linux时,您可能会发现这个脚本更适合您的需求,因为Perl预装在大多数Linux/Unix发行版上。

如果你需要创建一个带有IP地址的文件,你可以在命令行上做如下操作:

$ seq -f "192.168.0.%g" 1 255 > ip_range.txt

这将为您创建IP范围从192.168.0.1到192.168.0.255的文件,然后您可以使用我的脚本来ping这个范围:

$ perl ping_hosts.pl ip_range.txt

出于验证目的,我刚刚用694台主机重新运行了这个脚本,其中128台主机的主机名错误,它在1分6秒内返回了输出。

real    1m6.281s
user    0m0.265s
sys     0m0.137s

ping_hosts.pl

#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
my (@alive_hosts, @dead_hosts);
my $in_file = $ARGV[0];
open *DATA, "<", $in_file or die "$!n" if $in_file;
my @data = <DATA>;
chomp @data;
#my %uniq;
#my @hosts = grep { ! $uniq{$_}++ } @data;
my @hosts = keys %{{ map {lc $_ => 1} grep {/S/} @data }};
my $p = Net::Ping->new("icmp");
for my $host (@hosts) {
print "checking $host - ";
if ($p->ping($host)) {
print "upn";
push @alive_hosts, $host;
} else {
print "downn";
push @dead_hosts, $host;
}
}
print "n";
if (@alive_hosts) {
print "Possible alive hostsn";
print "=" x 10, "n";
print join "n", sort { $a cmp $b } @alive_hosts;
print "nTotal = ", scalar(@alive_hosts);
print "nn";
}
if (@dead_hosts) {
print "Hosts not responding to pingn";
print "=" x 10, "n";
print join "n", sort { $a cmp $b } @dead_hosts;
print "nTotal = ", scalar(@dead_hosts);
print "n";
}
__DATA__

CAVEAT:如果你在所有死主机上使用这个脚本,那么它将是一个超级慢的脚本。

最新更新