Click here to Skip to main content
13,351,954 members (83,222 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 30 Jul 2014

Checking Open Ports with Ruby

, 30 Jul 2014
Rate this:
Please Sign up or sign in to vote.
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 ""`

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 “″. This last part is important because many times Windows lists connections in duplicate.

@portList =

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 ""`
@portList =

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



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


About the Author

Grant Curell
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 GHIH. More info at

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 30 Jul 2014
Article Copyright 2014 by Grant Curell
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid