Wednesday 10 July 2013

python script to test VPN connectivity opens socket to IP addresses and ports

Quick script I  wrote to test VPN connections. It reads in a list (data.csv) of IP's and ports and attempts to open a socket to them, then reports the result.

#!/usr/bin/env python

# Import some needed modules
import socket
import re
import sys
import csv

# Function that will take input of a customer name an ip address and a port number
# It will attempt to open a socket to that IP/port and report on success or failure

def test_connection(customer, address, port):
        # Create a TCP socket
        s = socket.socket()
        # Set the socket timeout to 10 seconds
        s.settimeout(15)
        msg1 = "Attempting to connect to customer %s on IP %s and port %s" % (customer, address, port)
        print msg1

        try:
                s.connect((address, port))
                msg2 = "Connection to customer [ %s ] on IP [ %s ] and port [ %s ] was [ OK ]" % (customer, address, port)
                pl = print_and_log_this(msg2)
                # If we can connect return True
                return True
        except socket.error, e:
                # If we can't connect and get an error return False
                msg3 = "Connection to customer [ %s ] on IP [ %s ] and port [ %s ] has [ FAILED ] with error [ %s ]" % (customer, address, port, e)
                pl = print_and_log_this(msg3)
                return False
        s.close()

# Function to print a message on screen and append it to a log file
def print_and_log_this (message):
    print message
    logfile = open("testipandportlog.txt", "a")
    logentry = message + "\n"
    logfile.write(logentry)
    logfile.close()


# Main fucntion of the program (program starts here)
if __name__ == '__main__':

        # Read in lines from the csv file, each line should have the following information
        # Customer-name,IP-address,Port-number
        # For each line in the CSV use the fuction created above to check connectivity
        data = open("data.csv", "rb")
        reader = csv.reader(data)
        for line in reader:
                c = line[0]
                a = line[1]
                p = eval(line[2]) # convert string to int
                check = test_connection(c, a, p)

        # Close our handle on the file
        data.close()
        #exit()



No comments:

Post a Comment