Per-user traffic monitoring on OpenWRT
Today I had cause to want to track the per-user (per-MAC address, really) traffic counts on an OpenWRT-based router. There’s nothing I could see that was built in, so I dug around and found wrtbwmon, which is a pretty good script for this sort of thing. However, it doesn’t work with the OpenWRT version I’m running (Backfire (10.03, r20728).)
So here I document what I had to do to make it work.
To start with, grab my version of the script itself from here. I put this into /usr/local/bin on the router, and made it executable (chmod +x /usr/local/bin/wrtbwmon.)
Using crontab -e, add the following (modified as you like) to the crontab:
* * * * * /usr/local/bin/wrtbwmon setup br-lan
*/5 * * * * /usr/local/bin/wrtbwmon update /tmp/usage.db
1,6,11,16,21,26,31,36,41,46,51,56 * * * * /usr/local/bin/wrtbwmon publish /tmp/usage.db /tmp/www/usage.htm /usr/local/lib/macusers.txt
3 0 12 * * rm -f /tmp/usage.db
7 */6 * * * cp /tmp/usage.db /usr/local/lib/usage.db.bak
(the one with all the numbers is actually one long line, it may wrap on this page)
Line 1 sets up iptables to track everything it sees on the network, 2 and 3 save and write out the data every 5 minutes, and 4 resets the database when the monthly transfer quota resets. The last line backs up the database to flash every 6 hours, so that in case of power failure at most 6 hours of data are lost. The script expects the backup to be found in /usr/local/lib/usage.db.bak, so if you alter this, you’ll have to alter the script.
Running /etc/init.d/cron restart may be needed here to make the cron daemon reload the new commands.
Set up /usr/local/lib/macusers.txt to map MAC addresses to users to give a nicer output. For example:
00:aa:bb:cc:dd:ee,Person 1
11:22:33:44:55:66,Person 2
The MAC addresses should be lower case.
In /www/cgi-bin/usage I put:
#!/bin/sh
echo 'Content-Type: text/html'
echo 'X-Dummy: dummy'
echo
cat /tmp/www/usage.htm
The dummy header line is needed to work around a bug in the uhttp version on the router. chmod +x this also.
Now, you can go to http://IP_OF_ROUTER/cgi-bin/usage and it’ll give you an HTML table showing who’s been uploading and downloading what. Good for finding out who hasn’t capped their torrent client’s upload speed.
Update: added the backup cron job, updated the script to restore the backup if needed, also now adds totals to the display.