Saturday, September 6, 2014

Count Packet per Second. (Bash)

Hi, today i needed to find out how many packets per second flows through the interface.
I understand that there available many variations of such scripts, but for me was faster to code a new one, than to find one that will do exactly what i need

I think the simplest way to find out how many packets pass the interface is to use 'ifconfig' command.

When you run it, you can see RX packets and TX packets.
eth0      Link encap:Ethernet  HWaddr d8:c2:44:32:ba:39  
          inet addr:172.16.1.1  Bcast:172.16.255.255  Mask:255.255.0.0
          inet6 addr: fe80::2ad1:31ff:fe23:a455/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4420149 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2632000 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:6126039045 (6.1 GB)  TX bytes:202902499 (202.9 MB)
That info will extract with simple bash script:


#!/bin/bash

if [ $1 ]
then
        echo -e "\n"
        iface=$1
else
        echo -e "\n\tPPS: Packets Per Second."
        echo -e "\t------------------------"
        echo -e "\tUsage: $0 [interface]\n"
        exit 1
fi

rxtotal=0
txtotal=0
cnt=0
while :
do
        cnt=`expr $cnt + 1`
        rx=$(ifconfig $iface |grep "RX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        tx=$(ifconfig $iface |grep "TX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        sleep 1
        rx2=$(ifconfig $iface |grep "RX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        tx2=$(ifconfig $iface |grep "TX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        rxnow=`expr $rx2 - $rx`
        txnow=`expr $tx2 - $tx`
        rxtotal=`expr $rxnow + $rxtotal`
        txtotal=`expr $txnow + $txtotal`

        echo -n -e "RX: $rxnow, Avg: `expr $rxtotal / $cnt` | TX: $txnow, Avg: `expr $txtotal / $cnt`                       \r"
done

Usage:
# ./pps

 PPS: Packets Per Second.
 ------------------------
 Usage: ./pps [interface]


Output:
#./pps eth0

RX: 0, Avg: 12 | TX: 0, Avg: 7
That's all.

No comments:

Post a Comment