simple python port connector

Thank you, Python! You make things easy. I needed a script that would do something simple—give it a list of servers and ports and it would do a TCP socket connection to see if the service was responding. I want to run this before making firewall changes and then after I’ve done a temporary commit to make sure I didn’t FUBAR something.

My first thought was Perl but it turned out to be more work than I cared for since my not so good to begin with Perl skilz are very rusty. I figured it would be simple in Python and after a few minutes research found I was right. Here’s the script:

import socket

def checkhost(host, port):
    sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sd.connect((host, port))
        print "OK Connected to %s:%d" % (host, port)
        print "FAIL Could not connect to %s:%d" % (host, port)

To run it, just add a function call like:

checkhost(localhost, 53)

which would check the DNS service on localhost.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s