我对 Ruby 很陌生,所以任何帮助都会非常有用。 :)
我的目标是用我的程序做的是:
- 打开一个 txt 文件,其中包含存储的 IP 列表
- 逐个获取每个 IP 并对其进行 ping 操作
- 如果 IP 可访问,则返回 TRUE 值
- 如果无法访问 IP,则返回 FALSE 值
- 所有无法访问的 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
返回true
或false
,但它从不返回'true'
,因此这个条件将始终为假,条件表达式将始终计算else
分支。