-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathport_scanner.rb
67 lines (51 loc) · 1.25 KB
/
port_scanner.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'ipaddr'
require 'timeout'
require 'socket'
class IPRange
include Enumerable
def initialize(from, to)
@from = IPAddr.new from
@to = IPAddr.new to
end
def each
current = @from
until current > @to
yield current
current = current.succ
end
end
end
class PortScanner
attr_reader :open_ports
CommonPorts = [7,20,21,22,23,25,80,220,443,992,993,995,8080]
def initialize(from, to, timeout=0.01)
@from = from
@to = to
@timeout = timeout
@ip_range = IPRange.new(@from, @to)
@open_ports = []
end
def scan(*ports)
ports = CommonPorts if ports.empty?
@open_ports = []
@ip_range.each { |ip| ports.each { |port| connect(ip, port) } }
end
private
def socket
@socket ||= Socket.new(AF_INET, SOCK_STREAM, 0)
end
def connect(ip, port)
begin
Timeout::timeout(@timeout) { TCPSocket.new(ip.to_s, port ) }
@open_ports << "#{ip.to_s}:#{port}"
puts "Port Open: #{ip.to_s}:#{port}"
rescue Timeout::Error
puts "Port Closed: #{ip.to_s}:#{port}"
rescue => e
puts "Port Closed: #{ip.to_s}:#{port}"
end
end
end
scanner = PortScanner.new("172.16.24.0", "172.16.24.40")
scanner.scan(20,21,22,80,8080)
p scanner.open_ports