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)

加入讨论

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

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据