如何在Ruby中对远程主机的可达性进行ping

如何在Ruby中对远程主机的可达性进行ping,ruby,Ruby,我试着用 Ping.pingecho("10.102.52.42", 30) 用于远程主机的可访问性。即使我能够手动ping IP,该语句也返回null。 在Ruby中是否有一种有效的方法来确定远程机器的可访问性?我使用您需要安装的netpinggem。那么代码就很简单了: #!/usr/bin/env ruby require 'net/ping' def up?(host) check = Net::Ping::External.new(host) check.ping

我试着用

Ping.pingecho("10.102.52.42", 30)
用于远程主机的可访问性。即使我能够手动ping IP,该语句也返回null。
在Ruby中是否有一种有效的方法来确定远程机器的可访问性?

我使用您需要安装的
netping
gem。那么代码就很简单了:

#!/usr/bin/env ruby

require 'net/ping'

def up?(host)
    check = Net::Ping::External.new(host)
    check.ping?
end

chost = '10.0.0.1'
puts up?(chost) # prints "true" if ping replies

如果您在*nix机器(OSX/Linux/BSD…)上,您可以随时告诉Ruby(使用back ticks)使用命令行并保存结果

x = `ping -c 1 10.102.52.42`
# do whatever with X

-c1
参数告诉它运行一次。您可以将此设置为任何适合的数字。如果不设置
-c
,它将一直运行,直到中断为止,这将导致程序暂停。

使用外部、UDP、HTTP等进行Ping。根据需要进行修改。你可以在网站上阅读更多

一,

二,

三,

四,


在我看来,这是更好的答案,因为它是平台独立的。back tick操作符的使用非常依赖于平台。最佳答案。和前面的评论一样!这就是我一直在寻找的答案。谢谢
########################################################################
# example_pingexternal.rb
#
# A short sample program demonstrating an external ping. You can run
# this program via the example:external task. Modify as you see fit.
########################################################################
require 'net/ping'

good = 'www.rubyforge.org'
bad  = 'foo.bar.baz'

p1 = Net::Ping::External.new(good)
p p1.ping?

p2 = Net::Ping::External.new(bad)
p p2.ping?
########################################################################
# example_pinghttp.rb
#
# A short sample program demonstrating an http ping. You can run
# this program via the example:http task. Modify as you see fit.
########################################################################
require 'net/ping'

good = 'http://www.google.com/index.html'
bad  = 'http://www.ruby-lang.org/index.html'

puts "== Good ping, no redirect"

p1 = Net::Ping::HTTP.new(good)
p p1.ping?

puts "== Bad ping"

p2 = Net::Ping::HTTP.new(bad)
p p2.ping?
p p2.warning
p p2.exception
########################################################################
# example_pingtcp.rb
#
# A short sample program demonstrating a tcp ping. You can run
# this program via the example:tcp task. Modify as you see fit.
########################################################################
require 'net/ping'

good = 'www.google.com'
bad  = 'foo.bar.baz'

p1 = Net::Ping::TCP.new(good, 'http')
p p1.ping?

p2 = Net::Ping::TCP.new(bad)
p p2.ping?
ping-1.7.8/examples/example_pingudp.rb
########################################################################
# example_pingudp.rb
#
# A short sample program demonstrating a UDP ping. You can run
# this program via the example:udp task. Modify as you see fit.
########################################################################
require 'net/ping'

host = 'www.google.com'

u = Net::Ping::UDP.new(host)
p u.ping?