小技巧-用iptables统计网速占用

目前我在家里用的路由器是个装了ImmortalWrt的NX30 Pro路由器,由于内存只有256兆,默认没带网速统计和限制网速的插件,对于网络速度限制就有点困难,刚好这次网上找到了一个可以用iptables统计网速的脚本,简单记录下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#!/bin/sh
echo "Collecting data..."
echo ""
cat /proc/net/arp | grep : | grep ^192 | grep -v 00:00:00:00:00:00| awk '{print $1}'> mac-arp
iptables -N UPLOAD
iptables -N DOWNLOAD
while read line;do iptables -I FORWARD 1 -s $line -j UPLOAD;done < mac-arp
while read line;do iptables -I FORWARD 1 -d $line -j DOWNLOAD;done < mac-arp
sleep 1
echo "Download speed:"
echo ""
iptables -nvx -L FORWARD | grep DOWNLOAD | awk '{print $2/1024/1" KB/s ",$1/10" packets/s", $9}' | sort -n -r
echo ""
echo "Upload speed:"
echo ""
iptables -nvx -L FORWARD | grep UPLOAD | awk '{print $2/1024/1" KB/s ",$1/10" packets/s", $8}' | sort -n -r
while read line;do iptables -D FORWARD -s $line -j UPLOAD;done < mac-arp
while read line;do iptables -D FORWARD -d $line -j DOWNLOAD;done < mac-arp
iptables -X UPLOAD
iptables -X DOWNLOAD

首先是通过arp记录内网ip地址,然后添加UPLOADDOWNLOAD链,
然后为mac-arp文件中每个ip地址添加FORWARD规则,将流量导到UPLOADDOWNLOAD
等待1秒,统计下载和上传速度,计算KB/s,packets/s,再清理规则
然后对于上传占用高的,我们可以用

1
2
iptables -t mangle -I FORWARD 1 -s 192.168.x.x -m limit --limit 800/s --limit-burst 1000 -j ACCEPT
iptables -t mangle -I FORWARD 2 -s 192.168.x.x -j DROP

限制通过包的数量为800,不过这个不绝对精确