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

时间:2014-01-12 23:24:52

标签: ruby

我尝试使用

Ping.pingecho("10.102.52.42", 30)

用于远程主机的可访问性。即使我能够手动ping IP,此语句也会返回null。 有没有一种有效的方法来确定Ruby中远程机器的可达性?

3 个答案:

答案 0 :(得分:29)

我使用您需要安装的net-ping 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

答案 1 :(得分:2)

如果您使用的是* nix机器(OSX / Linux / BSD ...),您可以随时告诉Ruby(使用后退标记)来使用命令行并保存结果。

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

-c 1参数告诉它运行一次。您可以将其设置为您认为合适的任何数字。如果你没有设置-c,它会一直运行直到它被中断,这将导致程序停止。

答案 2 :(得分:1)

使用外部,UDP,HTTP等进行Ping操作。根据需要进行修改。您可以在ping-net git-repo了解更多信息。

1

########################################################################
# 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?

2

########################################################################
# 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

3

########################################################################
# 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?

4

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?