Python's way of detecting TCP ports on remote servers

  • 2020-04-02 14:38:37
  • OfStack

This example shows how python detects TCP ports on remote servers. Share with you for your reference. The details are as follows:

Python detects remote server TCP port code, this code can be used to do server monitoring utility


#!/usr/bin/env python 
#coding:utf-8 
#filename:tcp.py 
''' 
author: gavingeng 
date:  2011-12-14 09:35:59 
''' 
import socket 
import sys 
NORMAL=0 
ERROR=1 
TIMEOUT=5 
def ping(ip,port,timeout=TIMEOUT): 
  try: 
    cs=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
    address=(str(ip),int(port)) 
    status = cs.connect_ex((address)) 
    cs.settimeout(timeout) 
    #this status is returnback from tcpserver 
    if status != NORMAL : 
      print ERROR 
    else: 
      print NORMAL   
  except Exception ,e: 
    print ERROR 
    print "error:%s" %e 
    return ERROR 
  return NORMAL 
if __name__=='__main__': 
  if len(sys.argv) < 3 : 
    print ur' Please use the following format : ./tcp.py www.jb51.net 80' 
    sys.exit(1) 
  ip = sys.argv[1] 
  port = sys.argv[2] 
  try: 
    timeout = sys.argv[3] 
  except IndexError ,e: 
    timeout=TIMEOUT 
  ping(ip,port,timeout)

I hope this article has helped you with your Python programming.


Related articles: