Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Thursday, May 22, 2008

Ping echo check in Ruby, a dummy port scanner

Ping library in Ruby is fun to use,
it is easy to make it as a small port scanner

require "ping"

if ARGV.length != 3
puts "Usage: pingb machine_domain min max"
exit 0
end

for port in (ARGV[1].to_i..ARGV[2].to_i) do
if Ping.pingecho(ARGV[0],1,port) then
puts "Port #{port} open"
end
end

$ruby pingecho.rb slashdots.org 80 100
Port 80 open

Command line arguments in Ruby.

Using the array: ARGV

Example:

puts "No. of arguments:" << ARGV.length.to_s

puts "Loop elements"
for options in ARGV do
puts options
end

puts "Loop index"
for i in 0..ARGV.length-1
puts "#{i} #{ARGV[i]}"
end

$ ruby testcmd.rb one two three
No. of arguments:3
Loop elements
one
two
three
Loop index
0 one
1 two
2 three

Wednesday, May 21, 2008

Random Number with ruby

using rand

Generate a random number in integer

rand(range in max)

for e.g.
get a random number from 1 to 10

1+rand(10)

Why need to plus "1", because rand returns 0...max-1

irb(main):034:0> 1+rand(10)
=> 8
irb(main):035:0> 1+rand(10)
=> 2
irb(main):036:0> 1+rand(10)
=> 7
irb(main):037:0> 1+rand(10)
=> 5
irb(main):038:0> 1+rand(10)
=> 1
irb(main):039:0> 1+rand(10)

Random a floating point number,
calling rand with null argument, rand returns floating number in range [0,1]

for e.g. for range 1...10
1 + rand * 9

irb(main):079:0> 1 + rand*9
=> 5.85549064689046
irb(main):080:0> 1 + rand*9
=> 8.5913031102674
irb(main):081:0> 1 + rand*9
=> 5.84003966648288
irb(main):082:0> 1 + rand*9
=> 3.45730690493765
irb(main):083:0> 1 + rand*9
=> 9.07177615052255
irb(main):084:0> 1 + rand*9
=> 5.07483813090987
irb(main):085:0> 1 + rand*9
=> 8.22263965908269

Print without newline

use print for more control than puts.

irb(main):001:0> puts "Hello"
Hello
=> nil
irb(main):002:0> print "Hello"
Hello=> nil
irb(main):003:0>