zhendeaini123 发表于 2018-8-29 08:52:51

编写shell脚本统计某个时间段内本机的流量

  
下面是我的wlan0网卡的输出信息,你可以使用ifconfig 或者 ifconfig | sed -n '/wlan0/,10p' 获取显示的信息的格式
  wlan0   Link encap:EthernetHWaddr xx:xx:xx:xx:xx:xx
  inet addr:172.29.164.251Bcast:172.29.167.255Mask:255.255.248.0
  inet6 addr: 2001:da8:c803:4a57:e190:606f:3155:9369/64 Scope:Global
  inet6 addr: fe80::6e71:d9ff:fe0b:27f6/64 Scope:Link
  inet6 addr: 2001:da8:c803:4a57:6e71:d9ff:fe0b:27f6/64 Scope:Global
  UP BROADCAST RUNNING MULTICASTMTU:1500Metric:1
  RX packets:1305 errors:0 dropped:0 overruns:0 frame:0
  TX packets:647 errors:0 dropped:0 overruns:0 carrier:0
  collisions:0 txqueuelen:1000
  RX bytes:370741 (362.0 KiB)TX bytes:117872 (115.1 KiB)
  下面的脚本通过获取最后一行的RX、TX的信息,在两个时间点上获取,然后统计这一段时间内的总流量。
  最后打印输出统计信息在屏幕上。
  #!/bin/bash
  #network traffic statistics
  #Write by Ricardo.su 2015-04-30
  TIME_RANGE=10
  time=`date +%m"-"%d" "%k":"%M`
  rx_point_1=`ifconfig wlan0 | grep [[:space:]]RX.*TX | awk '{print $2}' | cut -c7-`
  tx_point_1=`ifconfig wlan0 | grep [[:space:]]RX.*TX | awk '{print $6}' | cut -c7-`
  sleep $TIME_RANGE
  rx_point_2=`ifconfig wlan0 | grep [[:space:]]RX.*TX | awk '{print $2}' | cut -c7-`
  tx_point_2=`ifconfig wlan0 | grep [[:space:]]RX.*TX | awk '{print $6}' | cut -c7-`
  rx_rs=$(((rx_point_2-rx_point_1)/1024))
  tx_rs=$(((tx_point_2-tx_point_1)/1024))
  echo "Date $time"
  echo "Average Network Traffic in $TIME_RANGE s: RX $rx_rs KB TX $tx_rs KB"
  


页: [1]
查看完整版本: 编写shell脚本统计某个时间段内本机的流量