嵌入式linux shell脚本统计历史流量数据

需要每天统计指定网卡的发送和接收流量,并获取当次的下挂终端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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值