如何 ping 存储在文本文件中的一组 IP 并验证 IP 在 Ruby 中可以访问或无法访问的位置?



我对 Ruby 很陌生,所以任何帮助都会非常有用。 :)

我的目标是用我的程序做的是:

  1. 打开一个 txt 文件,其中包含存储的 IP 列表
  2. 逐个获取每个 IP 并对其进行 ping 操作
  3. 如果 IP 可访问,则返回 TRUE 值
  4. 如果无法访问 IP,则返回 FALSE 值
  5. 所有无法访问的 IP 将写入另一个 txt 文件

以下是我从不同的在线帮助来源拼凑出来的程序:

require 'timeout'
require 'socket'
#PING LOGIC
class Ping 
def self.pingecho(host, timeout=5, service="echo")
puts host
begin
while(timeout) do
s = TCPSocket.new(host, service)     
s.close
end
rescue Errno::ECONNREFUSED
return true
rescue   Timeout::Error, StandardError 
return false 
end
return true
end
end
#opening the file with list of IPs
File.open('Ips.xml', 'r'). each do |line|    
hostip = line
#passing each line to the class for the ping test
if (p Ping.pingecho(hostip) == 'true')
return
else
#writing all non-reachable IPs to another file
File.open('Not reachable.txt','a') do |linea|
linea.puts hostip + "n"
end   
end
end

当我执行它时,这不会给我任何错误,但为 txt 文件中我知道可以访问的所有 IP 提供 FALSE 结果。

我知道该程序的所有组件都可以正常工作:如果我直接将IP传递给它,ping逻辑就可以正常工作(例如:p Ping.pingecho("10.40.220.34"((。

文件打开;读取;写入其他文件也可以正常工作,因为我单独测试了它们。

问题似乎出在 IP 从 txt 文件传递到类的方式上。

if (p Ping.pingecho(hostip) == 'true')

Ping::pingecho返回truefalse,但它从不返回'true',因此这个条件将始终为假,条件表达式将始终计算else分支。

最新更新