22 июля 2011 г.

Network interfaces traffic collector (Python)


Данный скрипт написан на Python и использует базу SQLite для сохранения данных по трафику. Рекомендуется скрипт поместить в крон на выполнение каждую минуту.
#!/usr/bin/python

import sqlite3, time, math
from datetime import date, timedelta

conn = sqlite3.connect("/opt/netstat_db.s3db")
res = conn.execute("select * from interfaces")
for row in res:
        now_tx = open('/sys/class/net/' + row[1] + '/statistics/tx_bytes').read()
        now_rx = open('/sys/class/net/' + row[1] + '/statistics/rx_bytes').read()
        cur_day = time.strftime("%d")
        cur_mon = time.strftime("%m")
        cur_year = time.strftime("%Y")
        data = conn.execute("select count(*) from stats where iface_id=? and day=? and month=? and year=?", (row[0],cur_day,cur_mon,cur_year))
        rows = data.fetchone()[0]
        if(rows > 0):
                data = conn.execute("select tx_bytes,rx_bytes from stats where iface_id=? and day=? and month=? and year=?", (row[0],cur_day,cur_mon,cur_year))
                entry = data.fetchone()
                prev_tx = entry[0]
                prev_rx = entry[1]
                razn_tx = int(now_tx) - prev_tx
                razn_rx = int(now_rx) - prev_rx
                if(razn_tx < 0):
                        mnozh = math.ceil(math.fabs(razn_tx) / math.pow(2,32))
                        razn_tx = ((math.pow(2,32)*mnozh) - prev_tx) + int(now_tx)
                if(razn_rx < 0):
                        mnozh = math.ceil(math.fabs(razn_rx) / math.pow(2,32))
                        razn_tx = ((math.pow(2,32)*mnozh) - prev_rx) + int(now_rx)
                conn.execute("update stats set tx_bytes=tx_bytes+?, rx_bytes=rx_bytes+? where iface_id=? and day=? and month=? and year=?", (razn_tx,razn_rx,row[0],cur_day,cur_mon,cur_year))
                conn.commit()
        else:
                v4era = date.today() - timedelta(1)
                prev_day = v4era.strftime("%d")
                prev_mon = v4era.strftime("%m")
                prev_year = v4era.strftime("%Y")
                data = conn.execute("select count(*) from stats where iface_id=? and day=? and month=? and year=?", (row[0],prev_day,prev_mon,prev_year))
                rows = data.fetchone()[0]
                if(rows > 0):
                        data = conn.execute("select tx_bytes,rx_bytes from stats where iface_id=? and day=? and month=? and year=?", (row[0],prev_day,prev_mon,prev_year))
                        entry = data.fetchone()
                        prev_tx = entry[0]
                        prev_rx = entry[1]
                        razn_tx = int(now_tx) - prev_tx
                        razn_rx = int(now_rx) - prev_rx
                        if(razn_tx < 0):
                                mnozh = math.ceil(math.fabs(razn_tx) / math.pow(2,32))
                                razn_tx = ((math.pow(2,32)*mnozh) - prev_tx) + int(now_tx)
                        if(razn_rx < 0):
                                mnozh = math.ceil(math.fabs(razn_rx) / math.pow(2,32))
                                razn_tx = ((math.pow(2,32)*mnozh) - prev_rx) + int(now_rx)
                else:
                        razn_tx = now_tx
                        razn_rx = now_rx

                conn.execute("insert into stats (iface_id,day,month,year,tx_bytes,rx_bytes) values (?, ?, ?, ?, ?, ?)", (row[0],cur_day,cur_mon,cur_year,razn_tx,razn_rx))
                conn.commit()
Файл базы с уже добавленными в нее интерфейсами можно скачать отсюда - http://sendfile.su/389433 Для редактирования базы под Windows можно использовать утилиту SQLite Admin (она бесплатна). Пользуемся на здоровье, если есть вопросы - обращайтесь. ЗЫ: скрипт предназначен для использования только в ОС Linux (BSD и прочие поделки не прокатят); поддерживает 32-битные системы в которых при превышении трафика в 4 гб системные счетчики сбрасываются.

Комментариев нет:

Отправить комментарий