Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Ping all nodes on the LAN subnet

This Ruby script attempts to ping all machines on the network 192.168.1.x and then save the results in an XML file.

   1  
   2  #!/usr/bin/ruby
   3  #file: pingall.rb
   4  
   5  require 'ping'
   6  require 'prettyxml'
   7  require 'rexml/document'
   8  include REXML
   9  
  10  ip_prefix = '192.168.1.'
  11  file_template = File.new('network_nodes_template.xml','r')
  12  buffer = file_template.read
  13  doc = Document.new(buffer)
  14  (1..254).each do |i| 
  15  
  16    Thread.new do
  17      doc.root.elements["records/node[#{i}]/active"].text = 'y'  if Ping.pingecho(ip_prefix + i.to_s, 1)
  18    end
  19  
  20  end
  21  
  22  file = File.new('ping_results.xml','w')
  23  file.puts doc.pretty
  24  file.close


output extract from ping_results.xml:
   1  
   2  <ping_results>
   3    <summary/>
   4    <records>
   5      <node>
   6        <address>192.168.1.1</address>
   7        <active>n</active>
   8      </node>
   9      <node>
  10        <address>192.168.1.2</address>
  11        <active>n</active>
  12      </node>
  13      <node>
  14        <address>192.168.1.3</address>
  15        <active>n</active>
  16      </node>
  17  ...
  18      <node>
  19        <address>192.168.1.101</address>
  20        <active>n</active>
  21      </node>
  22      <node>
  23        <address>192.168.1.102</address>
  24        <active>y</active>
  25      </node>
  26      <node>
  27        <address>192.168.1.103</address>
  28        <active>y</active>
  29      </node>
  30  ...
  31      <node>
  32        <address>192.168.1.253</address>
  33        <active>n</active>
  34      </node>
  35      <node>
  36        <address>192.168.1.254</address>
  37        <active>y</active>
  38      </node>
  39    </records>
  40  </ping_results>


References:
- Ruby Threading [dzone.com]
- Pretty Print XML using Ruby [dzone.com]

Enumerable all

Source: Enumerating Enumerable: Enumerable#all? [globalnerdy.com]

Enumerable#all? and Arrays

When used on an array and a block is provided, all? passes each item to the block. If the block never returns false or nil during this process, all? returns true; otherwise, it returns false.
   1  
   2  # "feta" is the shortest-named cheese in this list
   3  cheeses = ["feta", "cheddar", "stilton", "camembert", "mozzarella", "Fromage de Montagne de Savoie"]
   4  
   5  cheeses.all? {|cheese| cheese.length >= 4}
   6  => true
   7  
   8  cheeses.all? {|cheese| cheese.length >= 5}
   9  => false
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS