python端口检测代码_检测远程服务器tcp端口是否打开

发布时间:2020-06-19编辑:脚本学堂
python检测远程服务器tcp端口打开情况的代码,python服务器监控中经常需要检测端口是否打开,这段代码可以派上用场,需要的朋友做个参考。

代码:
 

复制代码 代码示例:
#!/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.plcxue.com 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)