Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have recently downloaded vnstat to monitor my Internet bandwidth usage. I have a limited data plan but my ISP provides unmetered bandwidth during off-peak hours (2:00 AM to 8:00 AM). So, I would like vnstat to report the data usage categorizing on-peak usage and off-peak usage separately.

I have gone through man vnstat but couldn't find any help in this regard. Would it be possible to to get two different stats for on-peak and off-peak hours using vnstat? If not, what alternatives are available to me to achieve the same?

share|improve this question
Many bandwidth usage questions remain without solution here :( ... Have you checked your ISP's site for usage data. I know that BSNL was quite bad in providing recent usage data. But maybe your ISP is better? – DK Bose Mar 17 '14 at 18:46
OUCH! I remember they used to update usage every Thursday and the site would go down near end of the month. Now I switched to my local cableTV guy for unlimited b/w scheme (but slowish speed; can't watch live streaming). – DK Bose Mar 18 '14 at 2:55
I wrote a program to pull interesting data out of the ISP's website; it might be useful in your case, as they should log the two rates individually. This uses PhantomJS to scrape the usage data. It's a bit alpha, but works for me. – halfer Apr 14 '14 at 14:30
@halfer Thanks for the link.. Although I don't know php/javascript (infact don't know much programming), would see if I could make use of it someday... Why don't you give an answer using that utility giving an example for one or two ISPs... that might come handy for some people.. :) – Aditya Apr 14 '14 at 14:37
No probs. No time to write a substantial answer atm, hence the comment - but might well do another time! – halfer Apr 14 '14 at 14:45
up vote 5 down vote accepted

AFAIK no bandwidth monitoring tool is better than vnstat. Unfortunately it does't support this feature. But you can achieve this by using multiple databases for vnstat.

Save the data for on peak hours to vnstat1 and for off-peak to vnstat2. Make a daemon script that will switch them based on time of the day using an if condition in an infinite loop; if not between 02-08 hours use vnstat1 else disable vnstat1, enable vnstat2 and sleep.

I wrote the following bash script. Save it in a file and make it executable using sudo chmod x <filename>. Test it for some time. Finally make the script auto start with OS. Run it as the root user. (Just add the path to the script in /etc/rc.local for it to be executed at boot time).


# Select the interface to monitor e.g: eth0, eth1, ppp0

# Location of database used by vnstat
db1='/var/lib/vnstat1'   # on-peak
db2='/var/lib/vnstat2'   # off-peak



# Create database for db1 if it doesn't exist
if ! [ -d "$db1" ]
    mkdir -p "$db1"
    vnstat -i $i --dbdir "$db1" -u

# Create database for db2 if it doesn't exist
if ! [ -d "$db2" ]
    mkdir -p "$db2"
    vnstat -i $i --dbdir "$db2" -u

$debug && echo 1
#vnstat -i $i --disable

while true
    t=$( date  %H )
    $debug && t=$( date  %S )
    if [ "$t" -lt 2 ] || [ "$t" -gt 7 ]    # if peak hours
        $debug && echo 'On-peak hours'
        vnstat -i $i --dbdir "$db1" -u
        $debug && echo 2
        if [ "$iscatdata" ]
            vnstat -i $i --dbdir "$db2" > "$offpeakdb"
        vnstat -i $i --dbdir "$db1" > "$onpeakdb"
        if [ $current != 1 ]
            vnstat -i $i --disable --dbdir "$db2"
            $debug && echo 3
            vnstat -i $i --enable --dbdir "$db1" --sync
            $debug && echo 4
        $debug &&  echo 'Off-peak hours'
        vnstat -i $i --dbdir "$db2" -u
        $debug && echo 5
        if [ "$iscatdata" ]
            vnstat -i $i --dbdir "$db1" > "$onpeakdb"
        vnstat -i $i --dbdir "$db2" > "$offpeakdb"
        if [ $current != 2 ]
            vnstat -i $i --disable --dbdir "$db1"
            $debug && echo 6
            vnstat -i $i --enable --dbdir "$db2" --sync
            $debug && echo 7
    $debug && sleep 1 || sleep 1m

#### Notes
# Ignore this message at first execution
# Interface "lo" is already disabled.
# Interface "lo" is already enabled.

#For debugging use interface 'lo' then
# `ping -s 2222`

Change i=eth0 on 5th line to the network interface you want to monitor.

To know the usage run cat /tmp/onpeak and cat /tmp/offpeak respectively.

Also it's a good idea to reset the data on the default database (/var/lib/vnstat), as it will never update if everything in the script goes well.

share|improve this answer

Hopefully this helps a bit.

So I am going to give you a program I wrote, because I was having problems with cron working. I don't know shell scripting unfortunately so this is in python, but it worked for me, and it is pretty simple, but nice. Sorry I didn't comment my code, but I really didn't want to go back through it. I know some parts might not be the best, but it works.

def main():    
    while True:
        import time
        import os
        from subprocess import call
        interface=" "
        while interface==" ":

Enter your interface:
(Be careful there is no error checking for this part)
Examples are eth0, wlan0...
            if interface == "":

        while True:
            x= clogger(schedule[2],schedule[3],schedule[4],\

            if x== "done":
        while True:
            x= exit_q()
            if x== "y":
How would you like your output?
Type (From vnstat --longhelp):
     q,  --query          query database
     h,  --hours          show hours
     d,  --days           show days
     m,  --months         show months
     w,  --weeks          show weeks
     t,  --top10          show top10
     s,  --short          use short output
                call(["vnstat", "-"+str(user_exit), "-i", str(interface),])

def tim3():
    import time

    #current_time=["16", "20"]
    tim3= time.strftime("%H %M")

        """+ str(tim3)+"""
        Current time
    ui = inputs()
    newlist=[hour, minute]
    return schedule
def inputs():
    while True:
        start_hour=(input("Enter the starting hour (24hr): "))
        start_min=(input("Enter the starting minute: "))
        x = checker(start_hour, start_min)
        endh=(input("How many hours would you like to run? "))
        endm=(input("How many minutes would you like to run? "))
        y = checker(endh,endm)
        if str(x)=="Great":
            if str(y) == "Great":
                return [start_hour, start_min, endh, endm]

def checker(h,m):
    message=("Incorrect Format")
    while error==0:
        if h =="":
        if len(str(h))> 2:
        if m =="":
        if len(str(m))>2:
        for x in str(h):
            if x.isdigit() == False:
            if error>0:     
        for y in str(m):
            if y.isdigit() == False:
            if error>0:     

def clogger(s1,s2,t1,t2,I):
    import time
    import os
    from subprocess import call

    while True:
        if len(str(s1))<2:

        if len(str(s2))<2:

        if len(str(h1))<2:

        if str(h1)==str(s1) and str(m2)==str(s2):
            while True:
                if total_time>0:

                    call (["vnstat", "-i",str(I)])
                    print(total_time," seconds")

                elif total_time<=0:
                    return "done"


def exit_q():

    while True:
        question=input("Would you like to show a report? (y/n) ")
        if question == "y" or question == "n":
            return question


Quick Guide

  • Open up Idle, copy>paste.

  • Save as

  • Open Terminal.

  • Run it with Python 3 (python3`).

  • Put in the hour you want to schedule for vnstat to run.

  • Put in the minute you want of that hour.

  • Put the amount of hours you want it to monitor for.

  • Put the amount of minutes you want it to monitor for.

Enter the device you are monitoring (I didn't go through and error check, so if you enter something like monkeybutt, it will try and run vnstat -i monkeybutt, every 15 seconds, just Ctrl+C out).

The program will run through every 15 seconds to see if the time matches, it won't give any messages. It's meant to be run in the background. Once it starts, it will take a shot every 15 seconds of the network, on the device you chose. Using the vnstat command, plus a counter saying how many seconds you have left of monitoring.

After completing the scans it will ask if you want to exit, and give you an option if you want to show a report, otherwise you can just exit. All of the stuff is stored in vnstats database anyways.

Old part of post (may be helpful to some people)

You could get gnome-schedule, then put in your command for example vnstat -h, and set it reoccurring during times you are trying to monitor. Maybe too simple, but hopefully someone else could expand further.

Additional(Edit): I have not used vnstat very much, which is why I was hoping someone could expand on that part, but with the gnome-schedule, you can schedule a command to execute during specific parts of the day. So using vntstat -tr -l (traffic switch, monitor live traffic), would show the traffic while running (which you can schedule in gnome-schedule, but you may have to manually Ctrl+C] out.)

Otherwise I am sure you could pipe this into a file, or use the graphical output program for vnstat if you have that. Graphical output program is vnstati -i 'filename' will output it to png file. If you want further commands vnstat --longhelp has more commands.


(Sample screen of how to put things into gnome-schedule.)

Do you know how to get a 'snapshot' of the bandwidth using vnstat already, or do you need further help on those commands? I can try to work with the program more.

share|improve this answer
Why does it need to ask me all the time related stuff... I want it to continuously monitor the network usage and show data separately for on-peak hours and off-peak hours... I would like to see both the data whenever I want. Moreover, there are a couple of indentation bugs in this Python program... (I would try to clear them up if you don't do it in the meantime)... – Aditya Apr 10 '14 at 15:20
Yeah the indents get messed up on the forum, I have to run through every thing and add spaces, sorry about that. I could just post the py program somewhere I guess. Let me look into databases for this as well. – No Time Apr 11 '14 at 2:52
@Aditya, I looked at your error message from the script by totti. You will probably have to run it as sudo/root since the files that are being accessed/moved do not normally have user level permissions. I would test totti's script more, but I can't select time (or do a test now) to see if it is giving me good output. I would need to run it for about 8 hours, and really don't want to wait that long. I don't know shell script enough to fix it. if you could change it so it isn't as hard time set to see if it works, that would be cool. (I have no rep I can't comment on other ppl's stuff) – No Time Apr 11 '14 at 3:59
@totti maybe add a variable/user input time? – No Time Apr 11 '14 at 4:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.