#!/usr/bin/python import re import time import thread import getopt import signal import sys from subprocess import Popen, PIPE, STDOUT # TODO print not refreshing correctly def get_bytes_from_tcpdump(interface, src, byte_values): command = Popen(['tcpdump', '-n', '-e', '-p', '-l', '-v', '-i', interface, 'src', src], stdout=PIPE, stderr=PIPE, bufsize=0) while 1: line = command.stdout.readline() if not line: # time.sleep(1) continue bytes_pattern = re.search('length \d*', line) # dest_pattern = re.search('> .*: ', line) if bytes_pattern: s = bytes_pattern.group(0) bytes = int(s[7:]) + 5 else: # ARP packet bytes = 28 + 14 byte_values[0] += bytes byte_values[1] += 1 # time.sleep(1) # if dest_pattern: # s = dest_pattern.group() # dest = s[2:len(s)-2] def get_bytes_from_proc(interface, byte_values): wrap = 2**32 offset = read_proc(interface) while(1): current_bytes = read_proc(interface) increase = current_bytes - offset if increase < 0: increase = (wrap - (byte_values[0] % wrap)) + current_bytes byte_values[0] += increase offset = current_bytes time.sleep(1) def get_bytes_from_ifconfig(interface, byte_values): offset = read_ifconfig(interface) while(1): bytes = read_ifconfig(interface) byte_values[0] += (bytes - offset) offset = bytes time.sleep(1) def read_ifconfig(interface): command = Popen(['/sbin/ifconfig', interface], stdout=PIPE, stderr=PIPE) # received bytes # lines = command.communicate()[0].split()[34] # transmitted bytes try: s = command.communicate() except Exception, e: print "failed: %r" % e bytes = int(s[0].split()[38].split(':')[1]) return bytes def read_proc(interface): f = open('/proc/net/dev') for line in f: values = line.split() i = values[0].split(':')[0] if interface == i: bytes = int(values[8]) # received bytes # bytes = int(values[0].split(':')[1]) f.close() return bytes f.close() def signal_handler(signum, frame): # print "bye" sys.exit(0) def main(interface, host): signal.signal(signal.SIGINT, signal_handler) byte_value_tcpdump = [0, 0] byte_value_proc = [0] byte_value_ifconfig = [0] thread.start_new_thread(get_bytes_from_tcpdump, (interface, host, byte_value_tcpdump)) thread.start_new_thread(get_bytes_from_proc, (interface, byte_value_proc)) # thread.start_new_thread(get_bytes_from_ifconfig, (interface, # byte_value_ifconfig)) while 1: s = "TCPDUMP: %d (%d packets)\nPROC: %d" % (byte_value_tcpdump[0], byte_value_tcpdump[1], byte_value_proc[0]) print s time.sleep(1) def usage(): print "Usage: monitor -i interface (e.g. eth0) -m host_ip" if __name__ == "__main__": interface = None ip = None opts, args = getopt.getopt(sys.argv[1:], "hi:m:", ["help"]) for o, a in opts: if o == '-i': interface = a elif o == '-m': ip = a elif o in ['-h', '--help']: usage() sys.exit() if not interface or not ip: usage() sys.exit() main(interface, ip)