`

python检测远程tcp端口

 
阅读更多

今天帮运维的同学写了个用来检测远程服务器tcp端口的脚本,使用的是python的socket模块来做的,具体如下:

#!/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 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=TIMEOUT
	ping(ip,port,timeout)
 
0
0
分享到:
评论
3 楼 di1984HIT 2014-05-19  
写的不错。
2 楼 genggeng 2011-12-16  
william_ai 写道
单就实现功能而言,在linux下,我通常这么玩。
nc -v -z www.iteye.com 80


哈哈,谢谢提醒!

用nc比较多的是跟同事互传文件!
1 楼 william_ai 2011-12-15  
单就实现功能而言,在linux下,我通常这么玩。
nc -v -z www.iteye.com 80

相关推荐

Global site tag (gtag.js) - Google Analytics