多线程端口扫描

#!/usr/bin/ruby
# -*- coding: utf-8 -*-

require 'socket'
include Socket::Constants
require 'timeout'

if ARGV[0]
  ips = ARGV[0].split(/\s/)
else
  p 'need ARGV'
  exit
end
ports = 80..200 #端口列表

def scan ip,po
  print "\r", ip + ' ' + po.to_s
  begin
    sock=timeout(4){TCPSocket.open(ip,po)}
    puts " is Opend! "
    sock.close
  rescue Exception => e
    #puts "#{ip} :#{po} is Closed ~~~ "
  rescue Timeout::Error
    #puts "#{ip} :#{po} is Closed ~~~ "
  end
end
ips.each { |i|
  ports.each { |p|
    sleep 0.27 #太快会被路由器BAN
    Thread.new{scan i, p}
  }
}

sleep 1 while Thread.list.size != 1 

puts "\ndone"

编程技巧