preload
Automating Visio with Ruby Using Rake to Generate Ocra exe’s
Feb 10

Anyone who has ever worked with networks at one point or another always ends up running a telnet or ping command over and over again to generate traffic and check if one computer can talk to another. After running that command a couple dozen times, one starts to think that maybe it would be better to write a program to do this instead.

One of my customers has a number of RedHat servers that I’m not allowed to install any programing language like Ruby or Perl on that I would normally use to write such a program…however, they have a complete Python installation for some reason. Not to argue with fate, I wrote the following script to run my tests with:

#
# nettest.py
#
import sys
import socket
import time

host = sys.argv[1]
port = int(sys.argv[2])
# type => ["tcp" or "udp"]
type = sys.argv[3]
test = ""
if len(sys.argv) > 4 :
 test = sys.argv[4]

while 1 :
  if type == "udp":
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  else:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.settimeout(5)
  try:
    if type == "udp":
      s.sendto("--TEST LINE--", (host, port))
      recv, svr = s.recvfrom(255)
      s.shutdown(2)
      print "Success connecting to " + host + " on UDP port: " + str(port)
    else:
      s.connect((host, port))
      s.shutdown(2)
      print "Success connecting to " + host + " on TCP port: " + str(port)
  except Exception, e:
    try:
      errno, errtxt = e
    except ValueError:
      print "Cannot connect to " + host + " on port: " + str(port)
    else:
      if errno == 107:
        print "Success connecting to " + host + " on UDP port: " + str(port)
      else:
        print "Cannot connect to " + host + " on port: " + str(port)
        print e
  if test != "C" :
    sys.exit(0)

  s.close
  time.sleep(1)

This is run like so:

$> python nettest.py 10.x.x.x 80 tcp C

The first parameter is the IP address, then what port to connect to, then what protocol to use (tcp or udp), then an optional ‘C’ if you want continuous tests. The ‘C’ option attempts the connection once a second — very useful when trying to figure out why the router isn’t routing the way you think it should.

I actually upload this Python script from within a Ruby script on my PC to run a number of connectivity checks and report the results in an Excel spreadsheet. ;) If there is enough interest, I can always post that script too.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon

One Response to “Python Connectivity Check Script”

  1. Perl Connectivity Check Script | JohnAllen.us / KD7SEE.us Says:

    [...] is a follow-on to my Python Connectivity Check Script that I posted a while back. It functions the same way…its just written in Perl. I use both [...]

Leave a Reply