Tuesday, May 28, 2013

Monitor network traffic with vnStat on FreeBSD

vnStat is a console-based network traffic monitor. It keeps a log of hourly, daily and monthly network traffic for the selected interface(s).

In short, vnStat is a console-based network traffic monitor that uses the network interface statistics provided by the kernel as information source. This means that vnStat won't actually be sniffing any traffic and also ensures light use of system resources. Optional image output is available starting from version 1.7.

Install vnStat:
# cd /usr/ports/net/vnstat
# make config-recursive
# make install clean
# rehash

Installation Document can be found here:
# less /usr/local/share/doc/vnstat/INSTALL_BSD

Create a directory to store the vnStat database:
# mkdir -p /home/srv/bsd-mon/vnstat

Create the configuration file:
# cp /usr/local/etc/vnstat.conf.sample /usr/local/etc/vnstat.conf

Edit the configuration file:
# vi /usr/local/etc/vnstat.conf
### default interface
Interface "em0"

### location of the database directory
DatabaseDir "/home/srv/bsd-mon/vnstat"

Find out the active network interface:
# ifconfig -a
em0: flags=8843 metric 0 mtu 1500

Specify an interface and update its database for the first time:
# vnstat -u -i em0

Note: it is normal to see following message:

Error: Unable to read database "/home/srv/bsd-mon/vnstat/em0".
Info: -> A new database has been created.

Verify the vnStat database has been created:
# ls /home/srv/bsd-mon/vnstat

Add a new crontab job:
# crontab -e
### run vnstat update every 5 minutes if installed
*/5 * * * * root if [ -x /usr/local/bin/vnstat ] && [ `ls -l /home/srv/bsd-mon/vnstat/ | wc -l` -ge 1 ]; then /usr/local/bin/vnstat -u; fi

Note: the default database dir is /var/db/vnstat/. Make sure you do change it.
Note: crontab example can be found at /usr/local/share/doc/vnstat/vnstat-cron.

Make sure vnstat is running properly every 5 minutes by looking at the modified time:
# ls -l /home/srv/bsd-mon/vnstat

To view network traffic:
# vnstat

To view daily traffic:
# vnstat -d

To view monthly traffic:
# vnstat -m

To display traffic for the last 24 hours:
# vnstat -h

To display all time top10 traffic days:
# vnstat -t

To display traffic for 7 days, current and previous week
# vnstat -w

To display current transfer rate for the selected interface in real time until interrupted. Statistics will be shown after interruption if runtime was more than 10 seconds:
# vnstat -l

To display current transfer rate for the selected interface in real time until interrupted:
# vnstat -l -i em0


No comments: