iftop;awk
http://www.jbxue.com/LINUXjishu/29854.html
iftop输出文本:
interface: eth0
IP address is: 107.170.243.66
MAC address is: 04:01:1d:04:ffffffbd:01
awk处理iftop输出日志:
114.94.114.79 2.54Kb 2.54Kb
114.94.114.79 80b 80b
常用命令:
/usr/local/iftop10pre4/sbin/iftop -N -n -P -i eth0
将iftop保存成文本脚本,nohup到后台就行了。
#!/bin/bash
Ifconfig="/sbin/ifconfig"
eth="eth0"
while true; do
TIME=$(date +'%Y%m%d%H%M%S')
RXpre=$($Ifconfig ${eth} | grep bytes | awk '{print $2}'| awk -F":" '{print $2}')
TXpre=$($Ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
sleep 1
RXnext=$($Ifconfig ${eth} | grep bytes | awk '{print $2}'| awk -F":" '{print $2}')
TXnext=$($Ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
TotalRXMin=$(expr `expr ${RXnext} - ${RXpre}` / 1048576)
TotalTXMin=$(expr `expr ${TXnext} - ${TXpre}` / 1048576)
if [ ${TotalTXMin} -gt 0 ];then
echo "$(date +'%Y-%m-%d %H:%M:%S') Total Recive: ${TotalRXMin}MB/s,Total Transfer:${TotalTXMin}MB/s" >> /tmp/lvs-net-mon.log
fi
if [[ ${TotalTXMin} -ge 1 ]];then
/usr/local/iftop10pre4/sbin/iftop -i ${eth} -N -P -t -L 50 -s 1 > /tmp/${TIME}.log
Filecount=$(ls /data/tcpdump/lvsflow*|wc -l)
#if [[ ${Filecount} -lt 100 ]];then
# tcpdump -nn -i ${eth} -w /data/tcpdump/ -Z root -C 10 -W 5 &
#else
# continue
#fi
else
continue
fi
done
http://www.kafan.cn/edu/5611612.html
实现原理:
[chengmo@localhost ~]$ cat /proc/net/dev
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo:1068205690 1288942839 0 0 0 0 0 0 1068205690 1288942839 0 0 0 0 0 0
eth0:91581844 334143895 0 0 0 0 0 145541676 4205113078 3435231517 0 0 0 0 0 0
proc/net/dev 文件保存了网卡总流量信息,通过间隔一段间隔,将入网卡与出记录加起来。减去之前就得到实际速率。
程序代码:
复制代码
代码如下:
awk 'BEGIN{
OFMT="%.3f";
devf="/proc/net/dev";
while(("cat "devf) | getline)
{
if($0 ~ /:/ && ($10+0) > 0)
{
split($1,tarr,":");
net[tarr[1]]=$10+tarr[2];
print tarr[1],$10+tarr[2];
}
}
close(devf);
while((system("sleep 1 ")) >=0)
{
system("clear");
while( getline < devf )
{
if($0 ~ /:/ && ($10+0) > 0)
{
split($1,tarr,":");
if(tarr[1] in net)
{
print tarr[1],":",($10+tarr[2]-net[tarr[1]])*8/1024,"kb/s";
net[tarr[1]]=$10+tarr[2];
}
}
}
close(devf);
}
}'
说明:第一个while 是获得总的初始值,$1是网卡出流量,$10是网卡进流量。第2个while会间隔1秒钟启动一次。计算总流量差得到平均每秒流量。
注意:通过getline 逐行读取文件,需要close关闭 。否则在第2次while循环中不能获得数据。
运行结果: