python检测远程tcp端口
今天帮运维的同学写了个用来检测远程服务器tcp端口的脚本,使用的是python的socket模块来做的,具体如下:
#!/usr/bin/env python#coding:utf-8#filename:tcp.py'''author:gavingengdate:2011-12-14 09:35:59 '''import socketimport sysNORMAL=0ERROR=1TIMEOUT=5def 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 tcpserverif status != NORMAL :print ERRORelse:print NORMALexcept Exception ,e:print ERRORprint "error:%s" %ereturn ERRORreturn NORMALif __name__=='__main__':if len(sys.argv) < 3 :print ur'请按照如下格式使用: ./tcp.py 127.0.0.1 3306 5来使用'sys.exit(1)ip = sys.argv[1]port = sys.argv[2]try:timeout = sys.argv[3]except IndexError ,e:timeout=TIMEOUTping(ip,port,timeout)?nc -v -z www.iteye.com 80nc -v -z www.iteye.com 80