需要每天统计指定网卡的发送和接收流量,并获取当次的下挂终端IP/MAC,测试通过,历史流量信息保存到脚本同路径下的static,每次提取新数据会输出一份包含客户端列表和流量统计情况到临时文件供查看,脚本如下
#!/bin/bash
if ! [ -f ./static ]; then
#输出持久化文件头部标题
echo -e "ID TX(bytes) RX(bytes)\nSummation 0 0\n1 0 0" > static
fi
while true; do
current_time=$(date +%H:%M)
current_tx_bytes=$(cat /sys/class/net/usb0/statistics/tx_bytes)
current_rx_bytes=$(cat /sys/class/net/usb0/statistics/rx_bytes)
current_date=$(date +%Y%m%d)
#0点0分则插入新的记录
if [[ $current_time == '00:00' ]]; then
sed -i '3i '"$current_date"' 0 0' static
fi
#总流量统计
base_data=$(sed -n '2p' static)
base_tx_bytes=$(echo $base_data | awk '{print $2}')
base_rx_bytes=$(echo $base_data | awk '{print $3}')
#当前流量统计
config_data=$(sed -n '3p' static)
config_tx_bytes=$(echo $config_data | awk '{print $2}')
config_rx_bytes=$(echo $config_data | awk '{print $3}')
#设备重启,网卡数据归零,需要合并计算
if [[ $current_tx_bytes -lt $base_tx_bytes || $current_rx_bytes -lt $base_rx_bytes ]]; then
new_tx_bytes=$(( $config_tx_bytes + $current_tx_bytes ))
new_rx_bytes=$(( $config_rx_bytes + $current_rx_bytes ))
base_tx_bytes=$(( $base_tx_bytes + $current_tx_bytes ))
base_rx_bytes=$(( $base_rx_bytes + $current_rx_bytes ))
else
new_tx_bytes=$(( $config_tx_bytes + ( $current_tx_bytes - $base_tx_bytes )))
new_rx_bytes=$(( $config_rx_bytes + ( $current_rx_bytes - $base_rx_bytes )))
base_tx_bytes=$current_tx_bytes
base_rx_bytes=$current_rx_bytes
fi
#替换新数据
sed -i 's/'"$config_data"'/'"$current_date $new_tx_bytes $new_rx_bytes"'/' static
sed -i 's/'"$base_data"'/'"Summation $base_tx_bytes $base_rx_bytes"'/' static
#在线客户端列表标题
echo 'Online clients:' >/tmp/usage
echo 'IP MAC'| awk -F' ' '{printf "%-15s %-15s %s\n", $1, $2}' >>/tmp/usage
ip -4 neigh show dev br-lan | grep -E 'REACHABLE|STALE|DELAY' | awk -F' ' '{printf "%-15s %-15s %s\n", $1, $3}' >>/tmp/usage >>/tmp/usage
#流量统计列表标题
echo 'Traffic statistics:' >>/tmp/usage
cat static | awk -F' ' '{printf "%-15s %-15s %s\n", $1, $2, $3}' >>/tmp/usage
#延时,秒
sleep 60
done