Last active
January 1, 2025 19:52
-
-
Save sarjsheff/a863d2223a93c3893e7e0b796d0019bd to your computer and use it in GitHub Desktop.
openwrt traffic accounting by ip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# get statistics in json from console | |
ubus call traff all |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# opkg install python3 python3-ubus | |
import ubus | |
import subprocess | |
import sys | |
import threading | |
class UbusThread(threading.Thread): | |
def __init__(self,traff): | |
threading.Thread.__init__(self) | |
self.traff = traff | |
def run(self): | |
print("connect ubus") | |
ubus.connect('/var/run/ubus/ubus.sock') | |
def callback(handler, data): | |
handler.reply(traff) | |
ubus.add( | |
"traff", { | |
"all": {"method": callback, "signature": {}}, | |
}, | |
) | |
ubus.loop() | |
traff = {"download":{},"upload":{}} | |
u = UbusThread(traff) | |
u.start() | |
tdargs = ["tcpdump","-l","-q", "-nn", "-i", "eth0"] | |
p = subprocess.Popen(tdargs, stdout=subprocess.PIPE) | |
while p: | |
line = p.stdout.readline() | |
ppp = line.decode("utf-8").split(' ',6) | |
if len(ppp) < 7: | |
print(ppp) | |
if ppp[5] == "tcp": | |
sz = int(ppp[6].replace('\n','')) | |
f = ppp[2] | |
t = ppp[4].replace(':','') | |
s = traff["upload"].get(f,0) | |
traff["upload"][f] = s + sz | |
s = traff["download"].get(t,0) | |
traff["download"][t] = s + sz | |
elif ppp[5] == "UDP,": | |
pass | |
elif ppp[5] == "ICMP": | |
pass | |
elif ppp[1] == "ARP,": | |
pass | |
else: | |
print(ppp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment