Checking 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

 

Leave a Reply