Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Ruby

Checking Open Ports with Ruby

0.00/5 (No votes)
30 Jul 2014GPL3 6.7K  
How to check open ports with Ruby

Below is the code for listing open ports on a Windows box via Ruby.

portListRaw = `netstat -an | find "LISTENING" | find /V "0.0.0.0"`

This line first lists all active connections via netstat. The find “LISTENING” section lists those ports in a listening state. The “find /V” looks for any line without “0.0.0.0″. This last part is important because many times Windows lists connections in duplicate.

@portList = Array.new

This line creates a new array called portlist.

portListRaw.each_line{ |line|</span>

@portList.push((/:[0-9]{1,5}/.match(line)).to_s.delete ":")

}

portListRaw.each_line{|line| is a standard ruby function to iterate through all of the lines in portListRaw. At this juncture, each line of interest should have something like this <ip_address>:<port number>. We want to grab just the port number. To do this, we use the following function with regular expression embedded @portList.push((/:[0-9]{1,5}/.match(line)).to_s.delete “:”). The two ‘/’s denote the regular expression. What the line says is, “Match anything starting with a ‘:’ followed by one to five values between zero and nine.” Finally, the function deletes the ‘:’ with .to_s.delete “:”.

def getPorts(startPort, endPort)
portListRaw = `netstat -an | find "LISTENING" | find /V "0.0.0.0"`
@portList = Array.new

portListRaw.each_line{ |line|
@portList.push((/:[0-9]{1,5}/.match(line)).to_s.delete ":")

}
end

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)