2012-02-28 69 views
4

我有6個設備配置在IP地址1到255範圍192.168.1.X(其中X = 1到255)。我已經編寫了這個程序來ping通並查看可用的IP地址來執行操作。但它需要很長時間來執行... 任何人都可以提出一個快速的方法來執行此操作?從255的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 
+2

'-c'不是'timeout',而是'count'。要使用超時使用'-W'和/或'-w'。您也可以通過在單獨的線程中運行每個ping來加速這種情況,在這種情況下,您將在單次超時而不是255 *超時後收到所有響應。 – 2012-02-28 17:40:34

+1

或使用'nmap -sn 192.168.1.0/24' ping掃描:) – 2012-02-28 19:28:44

回答

2

測試用紅寶石1.9.3定時不壞;

[[email protected] ~]$ 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 
+1

[子進程](https://gist.github.com/1944010)在同一臺機器上的實現速度更快。 – 2012-02-29 20:04:13

相關問題