Home >Backend Development >Python Tutorial >python检测远程服务器tcp端口的方法

python检测远程服务器tcp端口的方法

WBOY
WBOYOriginal
2016-06-10 15:17:171288browse

本文实例讲述了python检测远程服务器tcp端口的方法。分享给大家供大家参考。具体如下:

python检测远程服务器tcp端口的代码,这段代码可以用来做服务器监控实用

#!/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'请按照如下格式使用: ./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)

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn