网卡流量监控工具vnstat的使用

前段时间因为网络的问题接触了一个名为vnstat的工具,这个工具实时监控网络的流量 ,直观地了解当前的网络情况。

vnstat源码有点难找,这个是我下载地址:http://humdi.net/vnstat/,上面有发布版本和最新的开发版本,我下载的是后者,版本是1.14。
这个工具的Makefile不复杂,是手工写的,所以如果要想交叉编译的话,把src目录的Makefile编译器CC改成交叉编译器就行了,十分简单。我一般用make来编译,不用make install来安装,生成的vnstat在src目录。要使用直接拷贝这个文件即可。
在使用时要注意一下。这个工具默认要创建目录/var/lib/vnstat的,但它不自己创建,而是判断目录是否存在。如果不存在的话,会提示:

1
2
3
Error: Unable to open database directory "/var/lib/vnstat": No such file or directory
The vnStat daemon should have created this directory when started.
Check that it is is configured and running. See also "man vnstatd".

所以,要你自己来创建。创建后,不带参数执行会报错(不是“抱错”)。如下:

1
2
3
4
5
6
7
#./vnstat
No database found, nothing to do. Use --help for help.
A new database can be created with the following command:
./vnstat --create -i eth0
Replace 'eth0' with the interface that should be monitored.
The following interfaces are currently available:
lo eth0 (100 Mbit)

上面的信息提示了要用–create来创建某个网卡的数据库,好,创建:

1
2
3
4
# ./vnstat --create -i eth0
Creating database for interface "eth0"...
Info: -A new database has been created.
Restart the vnStat daemon if it is currently running in order to start monitoring "eth0".

创建成功了。
使用命令“vnstat -?”可以查看帮助信息(为什么不是“-h”呢?因为“-h”表示hours),“-l”表示实时(live)数据,默认显示的流量是比特单位的,可以用“-ru”设置单位为比特还是字节(0表示字节,1表示比特)。默认监控的是eth0设备,可以使用“-i”来指定哪一个网卡。实时监控时,要用Ctrl+C来停止。
下面是一个示例:

1
2
3
latelee@latelee:/home/latelee/tools/vnstat-master/src# ./vnstat -l -ru 0
Monitoring eth0... (press CTRL-C to stop)
rx: 12.93 KiB/s 176 p/s tx: 11.73 MiB/s 8442 p/s

下面是某台电脑的测试情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# vnstat -l
Monitoring eth0... (press CTRL-C to stop)


rx: 30.57 MiB/s 506048 p/s tx: 0.00 KiB/s 0 p/s^C

eth0 / traffic statistics

rx | tx
--------------------------------------+------------------
bytes 548.96 MiB | 0 KiB
--------------------------------------+------------------
max 30.57 MiB/s | 0.00 KiB/s
average 30.50 MiB/s | 0.00 KiB/s
min 30.45 MiB/s | 0.00 KiB/s
--------------------------------------+------------------
packets 9087616 | 0
--------------------------------------+------------------
max 506048 p/s | 0 p/s
average 504867 p/s | 0 p/s
min 504000 p/s | 0 p/s
--------------------------------------+------------------
time 18 seconds

后来想了想,觉得自己可以改代码,把上面说的创建目录加进去,把流量单位默认改为字节。这样不用太多人为干预就可以达到想要的效果了。主要改了2个地方,在common.h文件将RATEUNIT改为0。

1
2
3
4
5
6
7
8
9
10
11
12
/* rate unit */
/* 0 = bytes, 1 = bits */
#define RATEUNIT 0
在vnstat.c文件添加创建目录代码:
/* check if the database dir exists and if it contains files */
if (!p.traffic && !p.livetraffic) {
char buffer1[128] = {0};
if ((dir=opendir(p.dirname)) == NULL) {
sprintf(buffer1, "mkdir %s", p.dirname);
system(buffer1);
}
}

2015.3.31,李迟