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-10 of 328 total  RSS 

Make a short link with Bit.ly

   1  link = 'http://www.wired.com'
   2  short_link = open('http://bit.ly/api?url=' + link, "UserAgent" => "Ruby-ShortLinkCreator").read
   3  # => "http://bit.ly/AvxfY"

Search and replace keywords within many files

# search and replace all text files in the temp directory replacing the word 'five' with 'six'

   1  glob_path, exp_search, exp_replace = 'temp/*.txt','five', 'six'
   2  Dir.glob(glob_path).each do |file| 
   3    buffer = File.new(file,'r').read.gsub(/#{exp_search}/,exp_replace)
   4    File.open(file,'w') {|fw| fw.write(buffer)}
   5  end


output before:

more t*.txt
::::::::::::::
t1.txt
::::::::::::::
123 five 789
::::::::::::::
t2.txt
::::::::::::::
123 four 6789
::::::::::::::
t3.txt
::::::::::::::
123 ... five five four three

output after:

more t*.txt
::::::::::::::
t1.txt
::::::::::::::
123 six 789
::::::::::::::
t2.txt
::::::::::::::
123 four 6789
::::::::::::::
t3.txt
::::::::::::::
123 ... six six four three

Fun with grep in Ruby

# a basic string search
   1  >> f = "fun sun dog"
   2  
   3  >> puts f.grep('sun')
   4  => nil
   5  
   6  >> puts f.grep(/sun/)
   7  => fun sun dog
   8  
   9  >> f = "fun Sun dog"
  10  
  11  >> puts f.grep(/sun/i)  # case-insensistive
  12  => fun Sun dog



# search a range of numbers in an array
   1  >> numbers = [1, 2, 3, 4, 5, 6, 8, 9]
   2  >> numbers.grep(3..6)
   3  => [3, 4, 5, 6]



# search a range of dates
   1  >> dates = [Date.new(2000, 1, 1), Date.new(2002, 2, 2), Date.new(2004, 3, 3), Date.new(2006, 4, 4)]
   2  >> dates.grep(Date.new(2001, 1, 1)..Date.new(2005, 1, 1)) {|date| date.to_s }
   3  
   4  => ["2002-02-02", "2004-03-03"]



# searching for a base class
   1  >> class Base;end
   2  => nil
   3  >> class Child1 < Base;end
   4  => nil
   5  >> class Child2 < Base;end
   6  => nil
   7  >> class NotAChild;end
   8  >> => nil
   9  >> objects = [Child1.new, NotAChild.new, Child2.new]
  10  => [#<Child1:0xb7a825c0>, #<NotAChild:0xb7a825ac>, #<Child2:0xb7a82598>]
  11  
  12  >> objects.grep(Base)
  13  => [#<Child1:0xb7a825c0>, #<Child2:0xb7a82598>]



# search all Ruby files in the temp directory containing the word 'ruby'
   1  exp_search ='ruby'
   2  >> Dir.glob('temp/*.rb').each {|file| File.readlines(file).each {|l| l.grep(/#{exp_search}/).each {|r| puts file + ' : ' + r}} }
   3  
   4  temp/hello.rb : #!/usr/bin/ruby
   5  temp/jabber_bot.rb : require 'rubygems'
   6  temp/jabber_bot.rb : require 'ruby-debug'
   7  => ["temp/hello.rb", "temp/jabber_bot.rb"]


Resource:
- Getting to Know the Ruby Core Classes: Enumerable#grep - O'Reilly Ruby [oreillynet.com]

HANDY ONE-LINERS FOR RUBY

Source: http://www.fepus.net/ruby1line.txt [fepus.net]
<snip>
HANDY ONE-LINERS FOR RUBY November 16, 2005
compiled by David P Thomas <davidpthomas@gmail.com> version 1.0

Latest version of this file can be found at:
http://www.fepus.net/ruby1line.txt

Last Updated: Wed Nov 16 08:35:02 CST 2005

FILE SPACING:

# double space a file
   1      $  ruby -pe 'puts' < file.txt

# triple space a file
   1      $  ruby -pe '2.times {puts}' < file.txt

# undo double-spacing (w/ and w/o whitespace in lines)
   1      $  ruby -lne 'BEGIN{$/="\n\n"}; puts $_' < file.txt
   2      $  ruby -ne 'BEGIN{$/="\n\n"}; puts $_.chomp' < file.txt
   3      $  ruby -e 'puts STDIN.readlines.to_s.gsub(/\n\n/, "\n")' < file.txt


NUMBERING:

# number each line of a file (left justified).
   1      $  ruby -ne 'printf("%-6s%s", $., $_)' < file.txt

# number each line of a file (right justified).
   1      $  ruby -ne 'printf("%6s%s", $., $_)' < file.txt

# number each line of a file, only print non-blank lines
   1      $  ruby -e 'while gets; end; puts $.' < file.txt

# count lines (emulates 'wc -l')
   1      $  ruby -ne 'END {puts $.}' < file.txt
   2      $  ruby -e 'while gets; end; puts $.' < file.txt


TEXT CONVERSION AND SUBSTITUTION:

# convert DOS newlines (CR/LF) to Unix format (LF)
# - strip newline regardless; re-print with unix EOL
   1      $  ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' < file.txt


# convert Unix newlines (LF) to DOS format (CR/LF)
# - strip newline regardless; re-print with dos EOL
   1      $  ruby -ne 'BEGIN{$\="\r\n"}; print $_.chomp' < file.txt


# delete leading whitespace (spaces/tabs/etc) from beginning of each line
   1      $  ruby -pe 'gsub(/^\s+/, "")' < file.txt


# delete trailing whitespace (spaces/tabs/etc) from end of each line
# - strip newline regardless; replace with default platform record separator
   1      $  ruby -pe 'gsub(/\s+$/, $/)' < file.txt


# delete BOTH leading and trailing whitespace from each line
   1      $  ruby -pe 'gsub(/^\s+/, "").gsub(/\s+$/, $/)' < file.txt


# insert 5 blank spaces at the beginning of each line (ie. page offset)
   1      $  ruby -pe 'gsub(/%/, "   ")' < file.txt
   2      FAILS! $  ruby -pe 'gsub(/%/, 5.times{putc " "})' < file.txt


# align all text flush right on a 79-column width
   1      $  ruby -ne 'printf("%79s", $_)' < file.txt


# center all text in middle of 79-column width
   1      $  ruby -ne 'puts $_.chomp.center(79)' < file.txt
   2      $  ruby -lne 'puts $_.center(79)' < file.txt


# substitute (find and replace) "foo" with "bar" on each line
   1      $  ruby -pe 'gsub(/foo/, "bar")' < file.txt


# substitute "foo" with "bar" ONLY for lines which contain "baz"
   1      $  ruby -pe 'gsub(/foo/, "bar") if $_ =~ /baz/' < file.txt


# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
   1      $  ruby -pe 'gsub(/foo/, "bar") unless $_ =~ /baz/' < file.txt


# substitute "foo" or "bar" or "baz".... with "baq"
   1      $  ruby -pe 'gsub(/(foo|bar|baz)/, "baq")' < file.txt


# reverse order of lines (emulates 'tac') IMPROVE
   1      $  ruby -ne 'BEGIN{@arr=Array.new}; @arr.push $_; END{puts @arr.reverse}' < file.txt


# reverse each character on the line (emulates 'rev')
   1      $  ruby -ne 'puts $_.chomp.reverse' < file.txt
   2      $  ruby -lne 'puts $_.reverse' < file.txt


# join pairs of lines side-by-side (like 'paste')
   1      $  ruby -pe '$_ = $_.chomp + " " + gets if $. % 2' < file.txt


# if a line ends with a backslash, append the next line to it
   1      $  ruby -pe 'while $_.match(/\\$/); $_ = $_.chomp.chop + gets; end' < file.txt
   2      $  ruby -e 'puts STDIN.readlines.to_s.gsub(/\\\n/, "")' < file.txt


# if a line begins with an equal sign, append it to the previous line (Unix)
   1      $  ruby -e 'puts STDIN.readlines.to_s.gsub(/\n=/, "")' < file.txt


# add a blank line every 5 lines (after lines 5, 10, 15, etc)
   1      $  ruby -pe 'puts if $. % 6 == 0' < file.txt


SELECTIVE PRINTING OF CERTAIN LINES

# print first 10 lines of a file (emulate 'head')
   1      $  ruby -pe 'exit if $. > 10' < file.txt


# print first line of a file (emulate 'head -1')
   1      $  ruby -pe 'puts $_; exit' < file.txt


# print the last 10 lines of a file (emulate 'tail'); NOTE reads entire file!
   1      $  ruby -e 'puts STDIN.readlines.reverse!.slice(0,10).reverse!' < file.txt


# print the last 2 lines of a file (emulate 'tail -2'); NOTE reads entire file!
   1      $  ruby -e 'puts STDIN.readlines.reverse!.slice(0,2).reverse!' < file.txt


# print the last line of a file (emulates 'tail -1')
   1      $  ruby -ne 'line = $_; END {puts line}' < file.txt


# print only lines that match a regular expression (emulates 'grep')
   1      $  ruby -pe 'next unless $_ =~ /regexp/' < file.txt


# print only lines that DO NOT match a regular expression (emulates 'grep')
   1      $  ruby -pe 'next if $_ =~ /regexp/' < file.txt


# print the line immediately before a regexp, but not the regex matching line
   1      $  ruby -ne 'puts @prev if $_ =~ /regex/; @prev = $_;' < file.txt


# print the line immediately after a regexp, but not the regex matching line
   1      $  ruby -ne 'puts $_ if @prev =~ /regex/; @prev = $_;' < file.txt


# grep for foo AND bar AND baz (in any order)
   1      $  ruby -pe 'next unless $_ =~ /foo/ && $_ =~ /bar/ && $_ =~ /baz/' < file.txt


# grep for foo AND bar AND baz (in order)
   1      $  ruby -pe 'next unless $_ =~ /foo.*bar.*baz/' < file.txt


# grep for foo OR bar OR baz
   1      $  ruby -pe 'next unless $_ =~ /(foo|bar|baz)/' < file.txt


# print paragraph if it contains regexp; blank lines separate paragraphs
   1      $  ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /regexp/' < file.txt


# print paragraph if it contains foo AND bar AND baz (in any order); blank lines separate paragraphs
   1      $  ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /foo/ && $_ =~ /bar/ && $_ =~ /baz/' < file.txt


# print paragraph if it contains foo AND bar AND baz (in order); blank lines separate paragraphs
   1      $  ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /(foo.*bar.*baz)/' < file.txt


# print paragraph if it contains foo OR bar OR baz; blank lines separate paragraphs
   1      $  ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /(foo|bar|baz)/' < file.txt


# print only lines of 65 characters or greater
   1      $  ruby -pe 'next unless $_.chomp.length >= 65' < file.txt
   2      $  ruby -lpe 'next unless $_.length >= 65' < file.txt


# print only lines of 65 characters or less
   1      $  ruby -pe 'next unless $_.chomp.length < 65' < file.txt
   2      $  ruby -lpe 'next unless $_.length < 65' < file.txt


# print section of file from regex to end of file
   1      $  ruby -pe '@found=true if $_ =~ /regex/; next unless @found' < file.txt


# print section of file based on line numbers (eg. lines 2-7 inclusive)
   1      $  ruby -pe 'next unless $. >= 2 && $. <= 7' < file.txt


# print line number 52
   1      $  ruby -pe 'next unless $. == 52' < file.txt


# print every 3rd line starting at line 4
   1      $  ruby -pe 'next unless $. >= 4 && $. % 3 == 0' < file.txt


# print section of file between two regular expressions, /foo/ and /bar/
   1      $  ruby -ne '@found=true if $_ =~ /foo/; next unless @found; puts $_; exit if $_ =~ /bar/' < file.txt


SELECTIVE DELETION OF CERTAIN LINES

# print all of file except between two regular expressions, /foo/ and /bar/
   1      $  ruby -ne '@found = true if $_ =~ /foo/; puts $_ unless @found; @found = false if $_ =~ /bar/' < file.txt


# print file and remove duplicate, consecutive lines from a file (emulates 'uniq')
   1      $  ruby -ne 'puts $_ unless $_ == @prev; @prev = $_' < file.txt


# print file and remove duplicate, non-consecutive lines from a file (careful of memory!)
   1      $  ruby -e 'puts STDIN.readlines.sort.uniq!.to_s' < file.txt


# print file except for first 10 lines
   1      $  ruby -pe 'next if $. <= 10' < file.txt


# print file except for last line
   1      $  ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-1]' < file.txt


# print file except for last 2 lines
   1      $  ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-2]' < file.txt


# print file except for last 10 lines
   1      $  ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-10]' < file.txt


# print file except for every 8th line
   1      $  ruby -pe 'next if $. % 8 == 0' < file.txt


# print file except for blank lines
   1      $  ruby -pe 'next if $_ =~ /^\s*$/' < file.txt


# delete all consecutive blank lines from a file except the first
   1      $  ruby -e 'BEGIN{$/=nil}; puts STDIN.readlines.to_s.gsub(/\n(\n)+/, "\n\n")' < file.txt


# delete all consecutive blank lines from a file except for the first 2
   1      $  ruby -e 'BEGIN{$/=nil}; puts STDIN.readlines.to_s.gsub(/\n(\n)+/, "\n\n")' < file.txt


# delete all leading blank lines at top of file
   1      $  ruby -pe '@lineFound = true if $_ !~ /^\s*$/; next if !@lineFound' < file.txt



If you have any additional scripts to contribute or if you find errors
in this document, please send an e-mail to the compiler. Indicate the
version of ruby you used, the operating system it was compiled for, and
the nature of the problem. Various scripts in this file were written or
contributed by:

David P Thomas <davidpthomas@gmail.com> # author of this document


Tue Jun 26 18:17:36 CDT 2007
* Thanks to Taylor Carpenter <taylor@codecafe.com> for feedback on improving redirection format.
</snip>

Search and replace filenames using Ruby

This script searches and replaces file names within a file directory.

   1  
   2  #!/usr/bin/ruby
   3  #file: bulkrenamefiles.rb
   4  
   5  class BulkRenameFiles
   6    def initialize(h)
   7      h[:dir] = '.' if [:dir].empty?
   8  
   9      files = Dir.entries(h[:dir])
  10  
  11      files.each do |f|
  12        next if f == "." or f == ".."
  13        oldFile = h[:dir] + "/" + f
  14        newFile = h[:dir] + "/" + f.gsub(/#{h[:exp_search]}/,h[:exp_replace])
  15        File.rename(oldFile, newFile)
  16      end
  17    end
  18  end
  19  
  20  if __FILE__ == $0 then
  21    brf = BulkRenameFiles.new(:dir => '.', :exp_search => '^_', :exp_replace => '')
  22  end


output before:
   1  -rwxr-xr-x 1 apache apache  178 Aug  2 16:29 class_template.xml
   2  -rwxr-xr-x 1 apache apache  106 Aug  2 16:29 _tasks_data_template.xml
   3  -rwxr-xr-x 1 apache apache  100 Aug  2 19:31 _tasks_today.xml
   4  -rwxr-xr-x 1 apache apache  909 Aug  2 19:31 _tasks.xsl
   5  -rwxr-xr-x 1 apache apache  106 Aug  2 19:56 _tasks2_data.xml
   6  -rw-r--r-- 1 apache apache  267 Aug  2 22:43 _tasks.xml
   7  -rwxr-xr-x 1 apache apache   56 Aug  5 02:10 _tasks_template.xml
   8  -rwxr-xr-x 1 apache apache 2686 Aug  8 19:53 index.xml
   9  -rwxr-xr-x 1 apache apache 2685 Aug  8 19:53 _tasks_data.xml


output after:

   1  -rwxr-xr-x 1 apache apache  106 Aug  2 16:29 tasks_data_template.xml
   2  -rwxr-xr-x 1 apache apache  178 Aug  2 16:29 class_template.xml
   3  -rwxr-xr-x 1 apache apache  100 Aug  2 19:31 tasks_today.xml
   4  -rwxr-xr-x 1 apache apache  909 Aug  2 19:31 tasks.xsl
   5  -rwxr-xr-x 1 apache apache  106 Aug  2 19:56 tasks2_data.xml
   6  -rw-r--r-- 1 apache apache  267 Aug  2 22:43 tasks.xml
   7  -rwxr-xr-x 1 apache apache   56 Aug  5 02:10 tasks_template.xml
   8  -rwxr-xr-x 1 apache apache 2685 Aug  8 19:53 tasks_data.xml
   9  -rwxr-xr-x 1 apache apache 2686 Aug  8 19:53 index.xml


Source: Renaming files using ruby! - by Ruby on Rails [rubyonrailsexamples.com]

*update: 12-Oct-08 @ 16:00 *

Here's a great one liner from rush [heroku.com]:

   1  dir['*.jpg'].each { |f| f.rename f.name.gsub(/thumb-/, 'thumbnail_') }

Running netstat in a Ruby system command

Source: Running another process - netstat example - Ruby example [wellho.net]

   1  
   2  fhi = IO.popen("netstat 3")
   3  while (line = fhi.gets)
   4        print line
   5          print "and"
   6  end


extract from the output :
   1  
   2  Active Internet connections (w/o servers)
   3  andProto Recv-Q Send-Q Local Address           Foreign Address         State    
   4     
   5  andtcp        0      0 kataia.local:41981      92-236-96-2:xmpp-client ESTABLISH
   6  ED 
   7  andtcp        0      0 kataia.local:46000      ec2-75-101-229-77.c:www TIME_WAIT
   8     
   9  andtcp        0      0 kataia.local:36042      192.168.1.107:6600      ESTABLISH
  10  ED 
  11  andtcp        0      0 kataia.local:60859      ec2-67-202-19-236.c:www TIME_WAIT
  12  ...
  13  andunix  3      [ ]         STREAM     CONNECTED     11570    /var/run/dbus/system_bus_socket
  14  andunix  3      [ ]         STREAM     CONNECTED     11569
  15  andunix  3      [ ]         STREAM     CONNECTED     11540    /var/run/dbus/system_bus_socket
  16  andunix  3      [ ]         STREAM     CONNECTED     11539
  17  andunix  2      [ ]         DGRAM                    11535
  18  andunix  3      [ ]         STREAM     CONNECTED     11518
  19  andunix  3      [ ]         STREAM     CONNECTED     11517
  20  andunix  2      [ ]         DGRAM                    11494

Scan ports in Ruby

The following code originated from RubyForge: Simple TCP/IP port scanner: Project Info [rubyforge.org], and then the XML feature for reading and outputting port number information was added.


   1  #!/usr/bin/ruby
   2  #file: portscan.rb
   3  
   4  require 'open-uri'
   5  require 'socket'
   6  require 'rexml/document'
   7  include REXML
   8  
   9  class PortScanner
  10  
  11    def initialize(host, xmlfileout='portscan_result.xml')
  12      high = 8192
  13      service_url = "http://rorbuilder.info/r/service_ports.xml"
  14      doc_result = main(service_url, host, high)
  15  
  16      File.new(xmlfileout,'w').puts(doc_result)
  17      
  18    end
  19  
  20    def main(url, host, high)
  21  
  22      buffer = open(url, "UserAgent" => "Ruby-PortScanner1.0")
  23      doc = Document.new(buffer)
  24  
  25      doc.root.elements.each('records/port') do |node|
  26        new_node = Element.new('open')
  27        new_node.text = 'n'
  28        node.add_element new_node
  29      end
  30  
  31      for port in 1 .. high
  32        begin
  33  	      s = TCPsocket.open(host, port)
  34          puts 'port ' + port.to_s
  35          node_port = doc.root.elements["records/port[number='#{port.to_s}']"]
  36          
  37          unless node_port.nil? 
  38            port_name = node_port.elements['name'].text.to_s
  39            node_port.elements['open'].text = 'y'
  40          else 
  41            port_name = 'unknown'
  42            add_port(:doc => doc , :port => port , :name => port_name, :description => '') 
  43          end
  44  
  45  	      printf "%s/%sopen\t%s\n", port, 'tcp'.ljust(11 - port.to_s.length), port_name
  46  
  47  	      s.close
  48        rescue Errno::ECONNREFUSED
  49  	      next
  50        end
  51      end
  52      return doc
  53    end
  54  
  55    def add_port(h)
  56      node_port = Element.new('port')
  57  
  58      add_child(node_port, 'number', h[:port])
  59      add_child(node_port, 'name', h[:name])
  60      add_child(node_port, 'description', h[:description])
  61      h[:doc].root.elements['records'].add_element node_port
  62    end
  63  
  64    def add_child(node,nodename, value)
  65      newnode = Element.new(nodename)
  66      newnode.text = value
  67      node.add_element(newnode)
  68    end
  69  
  70  end
  71  
  72  if __FILE__ == $0 then
  73    ps = PortScanner.new('192.168.1.106')  
  74  end


screen output:
   1  
   2  22/tcp      open        ssh
   3  80/tcp      open        www
   4  443/tcp     open        https
   5  513/tcp     open        login
   6  514/tcp     open        shell
   7  4369/tcp    open        unknown
   8  5222/tcp    open        xmpp-client
   9  5269/tcp    open        xmpp-server
  10  5280/tcp    open        unknown
  11  8000/tcp    open        unknown
  12  8001/tcp    open        unknown

xml output:

   1  
   2  <ports>
   3    <summary/>
   4    <records>
   5      <port>
   6        <number>1</number>
   7        <name>tcpmux</name>
   8        <description>TCP port service multiplexer</description>
   9      <open>n</open></port>
  10      <port>
  11        <number>7</number>
  12        <name>echo</name>
  13        <description/>
  14      <open>n</open></port>
  15      <port>
  16        <number>7</number>
  17        <name>echo</name>
  18        <description/>
  19      <open>n</open></port>
  20  ...
  21      <port>
  22        <number>5222</number>
  23        <name>xmpp-client</name>
  24        <description>Jabber Client Connection</description>
  25      <open>y</open></port>
  26      <port>
  27        <number>5222</number>
  28        <name>xmpp-client</name>
  29        <description/>
  30      <open>n</open></port>
  31      <port>
  32        <number>5269</number>
  33        <name>xmpp-server</name>
  34        <description>Jabber Server Connection</description>
  35      <open>y</open></port>
  36      <port>
  37        <number>5269</number>
  38        <name>xmpp-server</name>
  39        <description/>
  40      <open>n</open></port>
  41  ...
  42      <port>
  43        <number>60179</number>
  44        <name>fido</name>
  45        <description>fidonet EMSI over TCP</description>
  46      <open>n</open></port>
  47    <port><number>4369</number><name>unknown</name><description></description></po
  48  rt><port><number>5280</number><name>unknown</name><description></description></p
  49  ort><port><number>8000</number><name>unknown</name><description></description></
  50  port><port><number>8001</number><name>unknown</name><description></description><
  51  /port></records>
  52  

Convert the /etc/services file to XML

This Ruby script simply reads the port numbers from the Linux file /etc/services into a n XML file.

   1  
   2  #!/usr/bin/ruby
   3  #file: readportservices.rb
   4  
   5  require 'rexml/document'
   6  require 'prettyxml'
   7  include REXML
   8  
   9  class ReadPortServices
  10  
  11    def initialize(h)
  12      @services_filepath = h[:services]
  13      @xml_filepath = h[:xmlfile]
  14      main()
  15    end
  16  
  17    def add_node(doc, port, name, description)
  18      node = Element.new('port')
  19  
  20      add_child(node, 'number', port)
  21      add_child(node, 'name', name)
  22      add_child(node, 'description', description)
  23      doc.root.elements['records'].add_element node
  24    end
  25  
  26    def add_child(node,nodename, value)
  27      newnode = Element.new(nodename)
  28      newnode.text = value
  29      node.add_element(newnode)
  30    end
  31  
  32    def main()
  33      doc = Document.new('<ports><summary/><records/></ports>')
  34      summary_description = ''
  35  
  36      File.readlines(@services_filepath).each do |line|
  37          next if line[0] == ?# or line =~ /^$/
  38  
  39          name, port, protocol, description = line.match(/(^[a-z][0-9A-Za-z_.+-]*)\s+(\d+)\/(\w+).[^#]+#?.?(.+)?$/).captures
  40          add_node(doc, port, name, description)
  41      end
  42  
  43      #puts doc
  44      file= File.new(@xml_filepath, 'w')
  45      file.puts doc.pretty
  46      file.close
  47    end
  48  end
  49  
  50  if __FILE__ == $0 then
  51    rps = ReadPortServices.new(:services => '/etc/services', :xmlfile => 'service_ports.xml')
  52  end

Capture matching Regex results into variables in 1 line of code


   1  >> firstname, lastname = line1.match(/(\w+),\s+(\w+)/).captures

=> ["David", "Smith"]
   1  >> firstname

=> "David"
   1  >> lastname

=> "Smith"

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]
« Newer Snippets
Older Snippets »
Showing 1-10 of 328 total  RSS