在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 packets)而无需su-root。这实际上是我需要写的一个自动化程序的要求。对于我来说,以普通用户的身份运行ping(CentOS)实用程序并获得预期的结果似乎有点疯狂,但是尝试以普通用户的身份使用Net::ping是不可能的。
有什么想法吗?
克
最佳答案
ping
实用程序之所以工作是因为它是setuid—它以根权限运行,即使是由普通用户执行:
-rwsr-xr-x 1 root root 44168 May 7 2014 /bin/ping
不管你喜不喜欢,使用ICMP本质上需要根权限。你不能像普通用户那样做。
如果要检查连接,请考虑建立TCP连接。(或者,heck,一个完整的HTTP请求。)