我在IP地址1到255上配置了6个设备,范围为192.168.1.X(其中X = 1到255)。我已经编写了这个程序来ping并查看可用的IP地址来执行操作。但是执行这么长时间...... 任何人都可以建议一个快速的方法来执行此操作吗?
叉子的使用也很受欢迎......
以下是该计划:
server = "192.168.1"
for i in (1...255)
system("ping -q -c #{timeout} #{server}.#{i} 2&>/dev/null")
if $?.exitstatus == 0
# operations
end
end
答案 0 :(得分:2)
用ruby 1.9.3测试时机不错;
[slmn@uriel ~]$ time ruby ipmap.rb
"192.168.0.1"
"192.168.0.10"
real 0m2.393s
user 0m0.750s
sys 0m1.547s
如果您想对线程进行操作,我对这些区域进行了评论;
require 'ipaddr'
ips = IPAddr.new("192.168.1.0/24").to_range
threads = ips.map do |ip|
Thread.new do
status = system("ping -q -W 1 -c 1 #{ip}",
[:err, :out] => "/dev/null")
# you can do your operations in thread like this
# if status
# # operations
# end
# optional
Thread.current[:result] = ip.to_s if status
end
end
threads.each {|t| t.join}
# if you don't do your operations in thread
threads.each do |t|
next unless t[:result]
# operations
#optional
puts t[:result]
end