测试网络连通性的监听小程序

测试网络连通性的监听小程序

在和合作伙伴联调时,经常会涉及到开通防火墙,开墙后要测试连通性,一般使用telnet或者应用调用接口。
但很多时候,开墙时,应用还没有部署上线,没法直接调用接口测试,telnet 也不灵,因为端口没有启嘛 🙂
我们使用python临时启一个端口监听(一般是和应用启动端口相同),这样就可以很方便测试网络连通性了。

[code lang=python]
#!/usr/bin/env python
# Rocky 2016-10-22
# set up a tcp Server listen to a port
# ./zServer.py 1211

from socket import *
from time import ctime
import sys

print 'Length of sys.argv: ', len(sys.argv)

for i in range(1, len(sys.argv)):
print "Parameters: ", i, sys.argv[i]
print ''

if len(sys.argv) > 1:
# tcpServerSocket.bind(address) need an integer, so int()
port = int(sys.argv[1])
else:
port = 30000

host = ''
# port = 20166
buffersize = 1024
address = (host, port)

tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(address)
tcpServerSocket.listen(5)

while True:
# display listen port
print ""
print 'Listening ', address
print 'Waiting for connection…'
tcpClientSocket, addr = tcpServerSocket.accept()
print '…connected from: ', addr

while True:
data = tcpClientSocket.recv(buffersize)
if not data:
break
tcpClientSocket.send('[%s] %s' % (ctime(), data))

tcpClientSocket.close()
tcpServerSocket.close()

[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注