Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / Ruby

Checking Open Ports with Ruby

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Jul 2014GPL3 6.5K   1  
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)


Written By
United States United States
Grant is a specialist in computer security and networking. He holds a bachelors degree in Computer Science and Engineering from the Ohio State University. Certs: CCNA, CCNP, CCDA, CCDP, Sec+, and GCIH.

Comments and Discussions

 
-- There are no messages in this forum --