#!/usr/bin/python # # tcpbinder.py # # (c) 2013,2015 Todd Shadburn # # Licensed under the GNU GPL v2 # import sys import getpass import pickle import socket import select ########################################################################## # main ########################################################################## # Globals timeout = 5 infiles = None outfile = None # Parse and validate arguments argmod = '' try: import argparse argmod = 'argparse' except: try: from optparse import OptionParser argmod = 'optparse' except: print 'No argparse or optparse modules!' sys.exit(2) if argmod == 'argparse': parser = argparse.ArgumentParser(description='Utility for bulk testing of TCP connectivity.') parser.add_argument('--infile', nargs=1, help='(Mandatory)Input file containing hosts and ports to test.') parser.add_argument('--outfile', nargs=1, help='(Optional)File to output results to.') parser.add_argument('--timeout', nargs=1, help='(Optional)Connection timeout in seconds (default=5).') args = parser.parse_args() infiles = args.infile if not args.outfile is None: outfile = args.outfile[0] if not args.timeout is None: timeout = args.timeout[0] else: parser = OptionParser() parser.add_option('--infile', dest='infiles', help='(Mandatory)Input file containing IPs and ports to bind to.', metavar='FILE') (options, args) = parser.parse_args() if not options.infiles is None: infiles = [options.infiles] if infiles is None: print "You must supply at least one --infile argument." sys.exit(2) # Process any files provided on the command line socklist = [] for file in infiles: fd = open(file, 'r') for ln in fd: (host,ports) = ln.split(',', 1) portlist = ports.rstrip('\n').split(',') for port in portlist: rc = 0 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((host, int(port))) sock.listen(10) socklist.append(sock) print 'Successfully bound to %s:%s' % (host, port) except: print 'Unable to bind to %s:%s' % (host, port) print sys.exc_info()[0] fd.close() # Echo server on each port while 1: rsocklist, wsocklist, esocklist = select.select(socklist, [], [], 10) for sock in rsocklist: csock,addr = sock.accept() csock.send('You have connected to the service! Goodbye!\r\n') csock.close() # Close sockets for sock in socklist: sock.close() sys.exit(0)