Home

Tags

Сетевой монитор на python (linux)

2010-02-26 python linux

Простой сетевой монитор, парсит лог tcpdump, нужно запускать от рута

Вывод

$ sudo python sample.py
0.0kb/sec, full: 0.0kb
0.2kb/sec, full: 2.3kb
0.1kb/sec, full: 3.6kb
9.9kb/sec, full: 64.5kb
13.0kb/sec, full: 133.4kb
22.8kb/sec, full: 256.2kb

Исходник

# coding: utf-8

import re
import time

rel = re.compile(r'length (\d+?)$')

cmd = 'tcpdump'
import subprocess
PIPE = subprocess.PIPE
p = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE,
        stderr=subprocess.STDOUT, close_fds=True)
try:
    full = 0
    size = 0
    t1 = time.time()
    t2 = t1 + 5
    while True:
        s = p.stdout.readline()
        if not s: break

        d = rel.findall(s)
        if d: size += int(d[0])

        if time.time() > t2:
            t2 = time.time() - t1
            full += size
            print '%.1fkb/sec, full: %.1fkb' % (size/t2/1024,full/1024.0)
            size = 0
            t1 = time.time()
            t2 = t1 + 5

except Exception as e:
    print e

p.terminate()