Python script to check for opened ports

In another article, I’ve mentioned the use of netcat to check for a listener on remote port at particular machine.
Here’s another example, yet more enhanced, written in python. The original idea belongs to a member of unix.com forums, nickname [Ghostdog74], I believe, again, I’ve modified it a little bit to serve my needs.
Most of you probably work in a multi-server environment, where you have all kinds of OSes – Linux, UNIX, Windows, etc – so called “TheServerFarm” :)
As soon as you want to check whether a certain port is opened on a remote machine (iptables may be turned on) you can use the following python script :

#!/usr/bin/python

import socket
import sys

if ( len(sys.argv) != 2 ):
print "Usage: " + sys.argv[0] + " Enter IP or FQDN as argument"
sys.exit(1)

remote_host = sys.argv[1]

for remote_port in [21,22,23,25,80,139,139,389,443,445,3128,3306,3389]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(20)
try:
sock.connect((remote_host, remote_port))
except Exception,e:
print "%d closed " % remote_port
else:
print "%d open" % remote_port
sock.close()

The possible ports to be checked are listed in the following line :
for remote_port in [21,22,23,25,80,139,389,443,445,3128,3306,3389]
Those are just generic ports, you can change the numbers to suit your needs, if, for example, your applications are running on specific ports. Here’s a sample report :

[unixgate@unix.com ~]$ monports.py 10.10.1.21
21 closed
22 open
23 closed
80 open

Just change the IP address or supply Fully Qualified Domain Name.

Published in: on April 23, 2008 at 9:31 am Leave a Comment

The URI to TrackBack this entry is: http://unixgate.wordpress.com/2008/04/23/python-script-to-check-for-opened-ports/trackback/

RSS feed for comments on this post.

Leave a Comment