Custom Search

Saturday, October 31, 2009

Tracking Network Usage With a Shell Script

Every morning the daily output is waiting there for
me in my email. Part of the normal output under Ipkts
and Opkts shows what went through the interface:

Ipkts            Opkts
2999812      2509494

I don’t reboot very often but when I do, it seems the system
zeros this out and it starts all over again. I put together
a script that runs periodically from a cronjob:

#!/bin/sh
# Filename: netusage.sh

cd $HOME/bin
if grep ‘daily output’ $HOME/Mail/root/new/*; then
cat `grep -l ‘daily output’ ~/Mail/root/new/*` | \
grep xl0 |tail -1 |awk ‘{print $5}’ > ibytes.out
cat `grep -l ‘daily output’ ~/Mail/root/new/*` | \
grep xl0 |tail -1 |awk ‘{print $7}’ > obytes.out

else
echo “No daily output yet” > /dev/null 2>&1
fi
cd

At the end of the month I run another script to total
the network usage:

#!/bin/sh
# Filename: netusemonthly.sh
cd $HOME/bin
date > `date +”%Y%m%d”`_endofmonthnetuse.log
echo “” >> `date +”%Y%m%d”`_endofmonthnetuse.log
echo “Monthly Ibytes” >> `date +”%Y%m%d”`_endofmonthnetuse.log
cat *ibytes.out |awk ‘{ SUM += $1 } END { print SUM }’ >> \
`date +”%Y%m%d”`_endofmonthnetuse.log
echo “” >> `date +”%Y%m%d”`_endofmonthnetuse.log
echo “Monthly Obytes” >> \
`date +”%Y%m%d”`_endofmonthnetuse.log
cat *obytes.out |awk ‘{ SUM += $1 } END { print SUM }’ >> \
`date +”%Y%m%d”`_endofmonthnetuse.log
mv -f *ibytes.out *obytes.out rebytes/
mv -f *endofmonthnetuse.log rebytes/
cd

The file names I used probably look ludicrous and they are all
completely arbitrary. If you try this out you can use whatever
file names and paths suit your needs. The whole thing was done
just to learn more about scripting, awk, and so forth. Also, to keep
the numbers right after a reboot, I added the following to
/etc/rc.shutdown:

netstat -ivn |head -8 |tail -1 |awk ‘{print $5}’ > \
/home/useracct/bin/`date +”%Y%m%d%H:%M:%S”`_reboot_ibytes.out
netstat -ivn |head -8 |tail -1 |awk ‘{print $7}’ > \
/home/useracct/bin/`date +”%Y%m%d%H:%M:%S”`_reboot_obytes.out
chown useracct:useracct /home/useracct/bin/*reboot_*bytes*

Like I said, this was all done just for learning purposes.
Maybe you can find a way to use some variation of the idea
on your own system.

Cheers!

Labels: , , , ,

0 Comments:

Post a Comment

<< Home