2012-08-15 100 views
1
#!/usr/bin/perl 
use Net::Ping; 
$p = Net::Ping->new(); 
my $main_ip="$ARGV[0]"; 

if ($p->ping($main_ip,1)){ 
    $result=true; 
    print "$main_ip is alive \n"; 
}else{ 
    print "$main_ip is down \n"; 
} 

我正在使用上面的perl脚本来ping检查服务器。除了IP 192.168.0.168以外,它能够正常工作。perl ping失败

$ perl test.pl 192.168.0.168 

192.168.0.168下跌

]$ ping 192.168.0.168 

PING 192.168.0.168 (192.168.0.168) 56(84) bytes of data. 
64 bytes from 192.168.0.168: icmp_seq=1 ttl=64 time=0.304 ms 
64 bytes from 192.168.0.168: icmp_seq=2 ttl=64 time=0.355 ms 
64 bytes from 192.168.0.168: icmp_seq=3 ttl=64 time=2.94 ms 
64 bytes from 192.168.0.168: icmp_seq=4 ttl=64 time=0.388 ms 

--- 192.168.0.168 ping statistics --- 
4 packets transmitted, 4 received, 0% packet loss, time 3292ms 
rtt min/avg/max/mdev = 0.304/0.997/2.944/1.124 ms 

]$ ping 192.168.0.18 

PING 192.168.0.18 (192.168.0.18) 56(84) bytes of data. 
From 192.168.0.181 icmp_seq=2 Destination Host Unreachable 
From 192.168.0.181 icmp_seq=3 Destination Host Unreachable 
From 192.168.0.181 icmp_seq=4 Destination Host Unreachable 

--- 192.168.0.18 ping statistics --- 
4 packets transmitted, 0 received, +3 errors, 100% packet loss, time 3292ms 
pipe 3 

]$ perl test.pl 192.168.0.18 

192.168.0.18 is down 

我根本不知道连我都增加Ping超时,但结果相同

+0

真正的原因可能是在192.168.0.168的防火墙上,正如我在我的回答中所描述的那样... – CyberDem0n 2012-08-15 12:42:52

回答

4

上检查防火墙唯一我能想到的问题是,ping命令使用ICMP协议作为默认值,而Net::Ping使用TCP。您可以通过创建你的对象这样的切换Net::Ping到ICMP:

my $p = Net::Ping->new('icmp'); 

。注意到,这使得ICMP ping需要在Unix root权限。

+0

这对我有用。谢谢。但需要找出真正的原因。 – k119 2012-08-15 12:24:30

+1

如果有效,那么192.168.0.168后面的机器不会回应TCP ​​ping或者有防火墙阻止TCP ping。我怀疑真正的问题在于你的计划。 – tauli 2012-08-15 12:50:06

1

为了发送ICMP数据包,你必须有权限创建原始套接字,即具有根权限。
我想你ping.pl作为普通用户运行,但是你必须要根

ls -al `which ping` 
-rws--x--x 1 root root 39640 Dec 17 2011 /bin/ping 
^
    | 
    suid bit 

ping程序具有suid位,它允许以root权限运行ping程序。

默认情况下,Net :: Ping会尝试连接到echo端口(7/tcp),如果它获得ECONNREFUSED - 这意味着主机已启动但拒绝连接(无法在该端口上侦听)。如果超时连接中断,这意味着主机已关闭。

但是!我可以阻止通过防火墙7/TCP的所有连接:

iptables -I INPUT -p tcp --dport 7 -j DROP 

和...瞧,我得到的down代替alive

所以,你应该将failure pinged主机

+0

他写道:“它工作正常,除IP 192.168.0.168以外的所有情况”,所以我猜测必须有其他例外。此外,'Net :: Ping'模块不使用安装的ping程序。文档(http://perldoc.perl.org/Net/Ping.html)表示默认协议(tcp)不需要特殊权限。 – mpe 2012-08-15 11:50:35