Created
July 12, 2018 20:28
-
-
Save pbrandiezs/a6ed16efe067ec4d76ee05e02744564e to your computer and use it in GitHub Desktop.
Check open ports from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'timeout' | |
def is_port_open?(ip, port) | |
begin | |
Timeout::timeout(1) do | |
begin | |
s = TCPSocket.new(ip, port) | |
s.close | |
return true | |
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH | |
return false | |
end | |
end | |
rescue Timeout::Error | |
end | |
return false | |
end | |
targets = [ | |
{:ip => "172.217.12.142", :port => "80"}, | |
{:ip => "google.com", :port => "80"}, | |
{:ip => "1.2.3.4", :port => "80"}, | |
{:ip => "google.com", :port => "22"} | |
] | |
targets.collect do |target| | |
if is_port_open?(target[:ip], target[:port]) | |
puts "open - #{target[:ip]}, port #{target[:port]}" | |
else | |
puts "closed - #{target[:ip]}, port #{target[:port]}" | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment