Skip to content

Instantly share code, notes, and snippets.

@vergoh
Last active January 3, 2018 21:39
Show Gist options
  • Save vergoh/1619965f1132fda3412b1031c822be1e to your computer and use it in GitHub Desktop.
Save vergoh/1619965f1132fda3412b1031c822be1e to your computer and use it in GitHub Desktop.
Experimental vnstat --exportdb from version 1.x to version 2.x daily data import
#!/usr/bin/env python
import os
import sys
import sqlite3
def main(argv):
if len(argv) != 3:
print "Invalid params, expected: <dbfile> <interface> <exportfile>"
sys.exit(1)
dbfilename = argv[0]
interface = argv[1]
exportfile = argv[2]
if not os.path.exists(dbfilename):
print "Error: no such dbfile"
sys.exit(1)
if not os.path.exists(exportfile):
print "Error: no such exportfile"
sys.exit(1)
# get interface id
conn = sqlite3.connect(dbfilename)
dbcursor = conn.cursor()
dbcursor.execute('select id from interface where name=?', (interface,))
result = dbcursor.fetchone()
if not result:
print "Error: no such interface"
sys.exit(1)
interfaceid = result[0]
# process file
with open(exportfile, 'r') as f:
for line in f:
if not line.startswith('d;'):
continue
c = line.strip().split(';')
if len(c) != 8:
continue
if c[7] != '1':
continue
rx = int(c[3])*1024*1024 + int(c[5])*1024
tx = int(c[4])*1024*1024 + int(c[6])*1024
print "insert: %s %s %d %d" % (interfaceid, c[2], rx, tx)
dbcursor.execute('insert into day (interface, date, rx, tx) values (?, date(?, \'unixepoch\', \'localtime\'), ?, ?)', (interfaceid, c[2], rx, tx))
conn.commit()
conn.close()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment