我们知道使用ifconfig 可以查看网卡的数据,包含收发的字节数,就是流量。如
root@fetmx6ull-s:~# ifconfig eth0
eth0 Link encap:Ethernet HWaddr AA:CC:DD:EE:FF:DD
inet addr:192.168.0.232 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::a8cc:ddff:feee:ffdd%2124081920/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:13392 errors:0 dropped:0 overruns:0 frame:0
TX packets:11681 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1445631 (1.3 MiB) TX bytes:1114438 (1.0 MiB)
root@fetmx6ull-s:~#
我们看到,信息的最后一行包含收发数据,那么我们如何取出数据呢?
首先选出这一行数据,
root@fetmx6ull-s:~# ifconfig eth0 | grep "RX bytes"
RX bytes:1445631 (1.3 MiB) TX bytes:1114438 (1.0 MiB)
先取出接收的字节数,由于在:后面没有空格,不能使用awk来完成,当然取出“RX bytes:1445631”在慢慢分析也是可以的,这里我们使用替换模式
root@fetmx6ull-s:~# ifconfig eth0 | grep "RX bytes" | sed 's/RX bytes:// '
1447837 (1.3 MiB) TX bytes:1114438 (1.0 MiB)
这样第一个字符就是我们需要的并且后面带空格,这样就可以取出来了
root@fetmx6ull-s:~# ifconfig eth0 | grep "RX bytes" | sed 's/RX bytes:// ' | awk '{print $1}'
1447837
那么如何取出发送的,数字是不定的,没有办法从头开始替换,我们可以使用 .* 来替换所有匹配的字符。
root@fetmx6ull-s:~# ifconfig eth0 | grep "RX bytes" | sed 's/.*TX bytes://'
1114438 (1.0 MiB)
这样就将从第一个字符开始替换,一直替换道 以 “TX bytes:" 结尾,这样就剩下了发送的数据了,然后使用awk来取出来
root@fetmx6ull-s:~# ifconfig eth0 | grep "RX bytes" | sed 's/.*TX bytes://' | awk '{print $1}'
1114438
完成的脚本代码如下:
root@fetmx6ull-s:~# cat showeth0.sh
#!/bin/bash
while :
do
echo "eth0 infomation is :"
echo "eth0 receive : `ifconfig eth0 | grep "RX bytes" | sed 's/RX bytes://' | awk '{print $1}'`"
echo "eth0 send : `ifconfig eth0 | grep "RX bytes" | sed 's/.*TX bytes://' | awk '{print $1}'`"
sleep 5s
done
我们执行以下看看:先后台执行这个脚本,然后使用ping,看数据变化
ping 192.168.0.200
PING 192.168.0.200 (192.168.0.200): 56 data bytes
64 bytes from 192.168.0.200: seq=0 ttl=64 time=1.008 ms
eth0 infomation is :
eth0 receive : 1452780
eth0 send : 1114536
64 bytes from 192.168.0.200: seq=1 ttl=64 time=0.934 ms
64 bytes from 192.168.0.200: seq=2 ttl=64 time=0.951 ms
64 bytes from 192.168.0.200: seq=3 ttl=64 time=0.904 ms
64 bytes from 192.168.0.200: seq=4 ttl=64 time=0.922 ms
64 bytes from 192.168.0.200: seq=5 ttl=64 time=0.984 ms
eth0 infomation is :
eth0 receive : 1453354
eth0 send : 1115068
64 bytes from 192.168.0.200: seq=6 ttl=64 time=0.930 ms
64 bytes from 192.168.0.200: seq=7 ttl=64 time=0.957 ms
64 bytes from 192.168.0.200: seq=8 ttl=64 time=0.921 ms
64 bytes from 192.168.0.200: seq=9 ttl=64 time=0.961 ms
64 bytes from 192.168.0.200: seq=10 ttl=64 time=0.901 ms
eth0 infomation is :
eth0 receive : 1453928
eth0 send : 1115600
这样,我们10秒打印一次当前网卡走的流量。就能够随时发现异常了,方便吧!