无法使用Net :: Ping在Perl中使用外部主机进行Ping操作

时间:2015-02-27 20:05:03

标签: linux perl

在Perl(5.16.3)中,我尝试使用Net :: Ping来测试远程主机是否可用。我能够ping"内部"我认识的主持人在我公司的局域网内上网,但我无法ping通外部"那些。特别是,尝试ping www.google.com'失败。

我的代码:

#!/usr/bin/perl

use strict;
use warnings;
use Net::Ping;

my $hostname1 = 'prophet'; #internal
my $hostname2 = 'www.google.com'; #external

my $p;
my $rv1;
my $rv2;

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

$rv1 = $p->ping($hostname1);
$rv2 = $p->ping($hostname2);


print "Response1: $rv1\n";
print "Response2: $rv2\n";

产生这个结果:

[oracle@prophet:bin]$ ./ping_test
Response1: 1
Response2: 0
[oracle@prophet:bin]$

尽管使用(CentOS) ping 实用程序确实显示了“www.google.com”'可用:

[oracle@prophet:bin]$ which ping; ping www.google.com
/usr/bin/ping
PING www.google.com (64.233.177.105) 56(84) bytes of data.
64 bytes from 64.233.177.105: icmp_seq=1 ttl=46 time=15.6 ms
64 bytes from 64.233.177.105: icmp_seq=2 ttl=46 time=15.6 ms
64 bytes from 64.233.177.105: icmp_seq=3 ttl=46 time=15.7 ms
64 bytes from 64.233.177.105: icmp_seq=4 ttl=46 time=16.5 ms
^C
--- www.google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 15.614/15.884/16.547/0.394 ms
[oracle@prophet:bin]$

我意识到如果我这样做(在我的Perl程序中):

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

然后 su - root 在我运行程序之前,它会工作......

[oracle@prophet:bin]$ su root
Password:    
[root@prophet:bin]# ./ping_test
Response1: 1
Response2: 1
[root@prophet:bin]#

...但是,我希望能够使用Net :: Ping(w / icmp数据包),而必须 su - root 。它实际上是我需要编写的自动化程序的要求。我可以将 ping (CentOS)实用程序作为普通用户运行并获得预期结果,这对我来说似乎有点疯狂,但是尝试将Net :: Ping用作普通用户是不行的-go。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

ping实用程序有效,因为它是setuid - 它以root权限运行,即使是由普通用户执行:

-rwsr-xr-x 1 root root 44168 May  7  2014 /bin/ping

不管您喜欢与否,使用ICMP本身都需要root权限。你不能像普通用户那样做。

如果要检查连接,请考虑建立TCP连接。 (或者,heck,一个完整的HTTP请求。)