【问题标题】:Unable To Ping External Hosts Using In Perl Using Net::Ping在 Perl 中使用 Net::Ping 无法 Ping 外部主机
【发布时间】:2015-02-27 20:05:03
【问题描述】:

在 Perl (5.16.3) 中,我尝试使用 Net::Ping 来测试远程主机是否可用。我可以 ping 我知道在我公司的 LAN 中在线的“内部”主机,但我无法 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(带 icmp 数据包)而无需不必su - root。这实际上是我需要编写的自动化程序的要求。我可以以普通用户身份运行 ping (CentOS) 实用程序并获得预期的结果,这对我来说似乎有点疯狂,但尝试以普通用户身份使用 Net::Ping 是不行的-去。

有什么想法吗?

  • G

【问题讨论】:

  • 您可以以非 root 用户身份运行 ping 的原因是它使用 setuid root 或在某些系统上设置了 CAP_NET_RAW 功能。

标签: linux perl


【解决方案1】:

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

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

不管你喜不喜欢,使用 ICMP 本身就需要 root 权限。普通用户是做不到的。

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

【讨论】:

  • 可能的解决方法:如perlsec 中所述,在 C 中编写一个执行脚本和 setuid root 的包装器。
  • @ThisSuitIsBlackNot,太复杂了。只需使用 -c 选项执行 ping 实用程序并检查退出代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2018-08-29
  • 1970-01-01
  • 2015-03-17
  • 2014-10-15
相关资源
最近更新 更多