码迷,mamicode.com
首页 > 编程语言 > 详细

python 测试udp状态

时间:2016-10-17 18:24:13      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:

用python脚本测试两个机器之间的udp的延迟与丢包情况

#!/usr/bin/python
#-*- coding:UTF-8 -*-
import socket
import struct
import random
import time
import logging
#from __future__ import division

logFile = "/tmp/check_wzry_%s.log" % time.strftime("%Y-%m-%d")
logging.basicConfig(level=logging.DEBUG,
                    format=‘%(asctime)s SrvZCheck [%(funcName)s] %(levelname)s %(message)s‘,
                    datefmt=‘%Y-%m-%d %H:%M:%S‘,
                    filename=logFile,
                    filemode=‘a‘)

TCP_RSP_CODE = {
    0x00: "SUCCESS",
    0x01: "SERVER_FAIL",
    0x02: "NOT_ALLOWED",
    0x03: "NETWORK_UNREACHABLE",
    0x04: "HOST_UNREACHABLE",
    0x05: "REFUSED",
    0x06: "TTL_EXPIRED",
    0x07: "COMMAND_NOT_SUPPORTED",
    0x08: "ADDRESS_TYPE_NOT_SUPPORTED",
    0x09: "REQUEST_ERROR",
    0x0A: "ROUTE_ERROR",
    0xEF: "UNKNOWN_ERROR"
}

CONNECTION_TIMEOUT = 500
CONNECTION_ERROR = 501
FORWARD_ERROR = 600
FORWARD_RSP_ERROR = 601
INTERNAL_ERROR = 400
SUCCESS = 0x00


class Client(object):
    def __init__(self, sbServer, sbPort):
        self.sbServer = sbServer
        self.sbPort = sbPort
        self.serverAddr = (sbServer, sbPort)
        self.recvBuff = 1024
        self.testStr = ‘subaoTest‘
        self.tStrLen = len(self.testStr)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def setTimeout(self, t):
        self.socket.settimeout(t)

    def close(self):
        return self.socket.close()

    def connect(self):
        pass

    def __del__(self):
         self.socket.close()

class WzryMeasure(Client):

    def __init__(self, sbServer, sbPort):
        super(WzryMeasure, self).__init__(sbServer, sbPort)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.idx = 2052
        self.tid = 2053

    def __createMeasureData(self):
        ver = 0x01
        cmd = 0x01
        fin = 0xFE
        return struct.pack("!2B2HB", ver, cmd, self.idx, self.tid, fin)

    def __checkRspData(self, Data):
        ver, rsp, idx, tid, fin = struct.unpack("!2B2HB", Data)
        if rsp == 0x00 and fin == 0xFE:
            return rsp
        else:
            logging.warning("response data not match, [str: %s, end: %s]" % (rsp, fin))
            return rsp
    
    def forwardData(self):
        try:
    #        aaa = time.time()
            self.setTimeout(1)
            testData = self.__createMeasureData()
            self.socket.sendto(testData, self.serverAddr)
            rspData = self.socket.recv(self.recvBuff)
    #        bbb = time.time()
    #        print bbb - aaa
            return self.__checkRspData(rspData)
        except socket.timeout:
            logging.exception("Conntion ‘%s:%s‘ Timeout" % self.serverAddr)
            return CONNECTION_TIMEOUT
        except socket.error, e:
            super(WzryMeasure, self).close()
            logging.exception(e)
            return CONNECTION_ERROR
        except Exception, e:
            super(WzryMeasure, self).close()
            logging.exception(e)
            return INTERNAL_ERROR

    def run(self):
        return self.forwardData()

def run(obj, opt, echoServer):
    ret = 0
    for echo in echoServer:
        echoParts = echo.split(‘:‘)
        z = obj(opt.server, opt.port, echoParts[0], echoParts[1])
        code = z.run()
        ret = code
        if code == 0:
            break
    print ret

def check_loss():
    success_num = []
    delay = []
    for i in range(10):
        now = time.time()
        if Z.run() == 0:
            last = time.time()
            success_num.append(i)
            every_delay = last - now 
            delay.append(every_delay)
    return (10 - len(success_num))*10,sum(delay)/len(delay)

if __name__ == "__main__":
    import optparse
    parse = optparse.OptionParser(usage="usage: %prog [Options] echo_ip:echo echo_ip:port",
                                  version="%prog 1.0")
    parse.add_option("-s", "--server", dest="server", help="wzry ip", type="string" )
    parse.add_option("-p", "--port", dest="port", action="store", type="int", help="wzry port")
    parse.add_option("-P", "--testWzry", dest="prober", action="store_true",
                     help="Porber measure check", default=False)
    parse.add_option("-L", "--check_loss", dest="loss", action="store_true",
                     help="check udp loss", default=False)
    parse.add_option("-D", "--check_delay", dest="delay", action="store_true",
                     help="check udp delay", default=False)
    opt, args = parse.parse_args()
    Z = WzryMeasure(opt.server, opt.port)
    if opt.loss:
        print check_loss()[0]
    elif opt.delay:
        print check_loss()[1]
    else:
        print parse.print_help()

  使用方法:延迟:demo.py -s $host -p $port -P -D delay 

    丢包:demo.py -s $host -p $port -P -L loss

python 测试udp状态

标签:

原文地址:http://www.cnblogs.com/ylqh/p/5970715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!