Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Checking Open Ports with Ruby

, 30 Jul 2014 GPL3
Rate this:
Please Sign up or sign in to vote.
Below is the code for listing open ports on a windows box via Ruby. 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

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)

Share

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 grantcurell.com.

Comments and Discussions

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