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