#!/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)