如何解决更快的 Ping 方法?
我需要对 254 台主机执行 ping 扫描,例如X.X.X.1 - X.X.X.254 并将结果输出到文件以供以后操作。目前,我有一个 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 "up\n";
push @alive_hosts,$host;
} else {
print "down\n";
push @dead_hosts,$host;
}
}
print "\n";
if (@alive_hosts) {
print "Possible alive hosts\n";
print "=" x 10,"\n";
print join "\n",sort { $a cmp $b } @alive_hosts;
print "\nTotal = ",scalar(@alive_hosts);
print "\n\n";
}
if (@dead_hosts) {
print "Hosts not responding to ping\n";
print "=" x 10,sort { $a cmp $b } @dead_hosts;
print "\nTotal = ",scalar(@dead_hosts);
print "\n";
}
__DATA__
CAVEAT:如果您在所有死主机上使用此脚本,那么它将是一个超慢的脚本。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。