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)
    try:
        sd.connect((host, port))
        print "OK Connected to %s:%d" % (host, port)
    except:
        print "FAIL Could not connect to %s:%d" % (host, port)
        sd.close()

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s