文章标签 » tcpdump

backup:tcpdump计算每10秒的平均传输速度(含上下行)

#!/usr/bin/env python

import re,sys
import time
import os
import subprocess
import datetime
import signal

GET_LENGTH = re.compile(r'length (\d+):')
LOG = open('./tcp.log', 'a')
IP = '10.235.160.73' #针对指定站点
while True:
        total = 0
        start = time.time()
        tcpdump = subprocess.Popen('tcpdump -e -i eth0 -nn host %s' % IP, shell=True, stdout=subprocess.PIPE)
        for line in iter(tcpdump.stdout.readline, ''):
                rt = GET_LENGTH.findall(line)
                if len(rt):
                        total += int(rt[0])
                if time.time() - start >= 10:
                        os.kill(tcpdump.pid, signal.SIGKILL)
                        os.waitpid(-1, os.WNOHANG)
                        break

        log = '%s\t%s\n' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), total/(time.time() - start)/1024)
        print log,
        LOG.write(log)

通过tcpdump粗略了解web server的qps

如果关掉了web server的日志,又想知道qps怎样,可以用下这个tcpdump脚本
qps.sh

#0x4745=GE 0x504F=PO 分别匹配GET请求和POST请求
tcpdump -n -i eth0 dst port 80 and \( tcp[20:2]=0x4745 or tcp[20:2]=0x504F \) 1> /dev/null 2> /dev/tty &
#如果系统自带timeout命令,可以替代这种山寨限时方法
sleep 1
killall tcpdump
#结果中的packets captured基本代表了实时的qps

tcpdump使用详解