# TCP Pinger - tcping.py # Tim Sharpe, Jul 2005 # # Purpose. "Pings" hosts using TCP session rather than ICMP (that's being blocked # more and more). Defaults to TCP port 80 (HTTP), but can "ping" on any port. # # Revision List # Date Description #============================================================= # 07/18/2005 Original Coding. # 08/09/2005 Cleaned up and matured command-line options and their handling. # # import socket, time import sys # # Store program name and version for inclusion into the standard banner banner1='TCPing, v1.01' banner2='Copyright (C) 2005, Tim Sharpe . ' # # Print initial banner print banner1 + ', ' + banner2 print 'This program comes with ABSOLUTELY NO WARRANTY and is covered by the' print 'GNU General Public License, version 2. See the "license.txt"' print 'file for details. This is free software, and you are welcome to ' print 'redistribute it under conditions of the GNU General Public License.' print # # Set Defaults # Default to 5 tries limit=5 # Default to use the limit (overridden by the -t option) uselimit=1 # Default to TCP port 80 (HTTP) PORT=80 if len(sys.argv)<2: print 'usage:' print 'tcping.py [-n num] [-t] [-p port] host' print print 'where: -n num = Option to set the number of "pings"' print ' (default=5). Trumps the -t option.' print ' -t = Option to ping forever.' print ' -p port = Option to change TCP port from the default' print ' port 80 (HTTP). Must be an integer.' print ' host = Mandatory hostname or IP Address of host to' print ' "ping".' sys.exit() else: for x in range(len(sys.argv)): if sys.argv[x]=='-t': uselimit=0 if sys.argv[x]=='-n': try: limit=int(sys.argv[x+1]) except: print 'ERROR! Missing or invalid argument for "-n" option...Exiting!' sys.exit() if sys.argv[x]=='-p': try: PORT=int(sys.argv[x+1]) except: print 'ERROR! Missing or invalid argument for "-p" option...Exiting!' sys.exit() HOST=sys.argv[-1] str1='"Pinging" host \'' + HOST + '\' on TCP port ' + str(PORT) if uselimit==1: str1=str1 + ' for ' + str(limit) + ' repetitions...\n' else: str1=str1 + ' forever...\n' print str1 count=1 while 1: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1.0) starttime=time.time() try: s.connect((HOST, PORT)) except: print 'Try ' + str(count) + ' failed to connect. Waiting...' time.sleep(.5) count=count+1 if count>limit and uselimit==1:sys.exit() else: print 'Try ' + str(count) + ' connected! Waiting...' elapsed=1-(time.time()-starttime) s.close() count=count+1 if count>limit and uselimit==1:sys.exit() time.sleep(elapsed)