• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

ruby端口扫描程序

JAVA相关 水墨上仙 1673次浏览

ruby编写的简单端口扫描程序

转自:http://www.javaarch.net/jiagoushi/

ruby的端口扫描示例

最简单的示例:端口扫描通过一个tcp链接到某个ip地址上,看看tcp链接的端口是否开通



require 'socket' #socket library
 
def open_port(host, port)
  sock = Socket.new(:INET, :STREAM)
  raw = Socket.sockaddr_in(port, host)
  puts "#{port} open." if sock.connect(raw)
 
rescue (Errno::ECONNREFUSED)
  rescue(Errno::ETIMEDOUT)
end
 
def main(host, start_port, end_port)
  until start_port == end_port do
    open_port(host, start_port)
    start_port += 1
  end
end
 
main ARGV[0], ARGV[1].to_i, ARGV[2].to_i

执行下面一行,会输入1到100端口哪些处于开放状态



ruby scanner.rb localhost 1 100

另外一个改进的示例,通过Celluloid这个ruby包来处理actor模型的并行框架,通过调用sp.async.run.这个方法来异步执行,主线程可以继续执行下面的逻辑,



require 'celluloid'
require 'socket'
 
class ScanPort
  include Celluloid
 
  def initialize(port, host)
    @port = port
    @host = host
  end
 
  def run
    begin
      sock = Socket.new(:INET, :STREAM)
      raw = Socket.sockaddr_in(@port, @host)
 
    puts "#{@port} open." if sock.connect(raw)
 
    rescue
      if sock != nil
        sock.close
      end
    end
 
  end
end
 
def main
  host = ARGV[0]
  start_port = ARGV[1].to_i
  end_port = ARGV[2].to_i
 
  until start_port == end_port do
    sp = ScanPort.new start_port, host
    sp.async.run
 
    start_port += 1
  end
end
 
main


我们再做下改进,每个线程扫描一部分端口



require 'celluloid'
require 'socket'
 
class ScanPort
  include Celluloid
 
  def initialize(start_port, end_port, host)
    @start_port = start_port
    @end_port = end_port
    @host = host
  end
 
  def run
    until @start_port == @end_port do
      scan @start_port
      @start_port += 1
    end
  end
 
  def scan(port)
      begin
        sock = Socket.new(:INET, :STREAM)        #build the socket
        raw = Socket.sockaddr_in(port, @host)
 
        puts "#{port} open." if sock.connect(raw)
      rescue
        if sock != nil
          sock.close
        end
      end
    end
end
 
def main
  host = ARGV[0]
  start_port = ARGV[1].to_i
  end_port = ARGV[2].to_i
 
  segment_size = 100
 
  until start_port >= end_port do
    sp = ScanPort.new start_port, start_port + segment_size, host
    sp.async.run
 
    start_port += segment_size
  end
end
 
main


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明ruby端口扫描程序
喜欢 (0)
加载中……