Skip to content

Instantly share code, notes, and snippets.

@prahladyeri
Created November 11, 2015 16:11
Show Gist options
  • Select an option

  • Save prahladyeri/298d11fdb0a952e646aa to your computer and use it in GitHub Desktop.

Select an option

Save prahladyeri/298d11fdb0a952e646aa to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# author: Prahlad Yeri
# description: Script to track bandwidth consumption and put in database. Place this in /etc/NetworkManager/dispatcher.d/
import subprocess, os, datetime, sys
def execute(command):
try:
p=subprocess.Popen(command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p.wait()
result=p.communicate()
#print str(result)
if len(result[0])>0:
return result[0].strip()
else:
return result[1].strip()
except Exception as e:
print 'error occured:' + errorstring
return errorstring
if (len(sys.argv))<2:
print "Not enough args"
#main
#mypath = '/etc/NetworkManager/dispatcher.d/'
mypath = '/var/lib/netstatgui/'
if (not os.path.exists(mypath)):
os.mkdir(mypath)
iface = sys.argv[1].strip()
status = sys.argv[2].strip()
log=open(mypath + 'netstatgui.log','a')
#log.write(iface + ':' + status + '\n')
#log.close()
for part in sys.argv:
log.write(part + ' ')
log.write('\n')
tfp = open('/proc/net/dev','r')
proc_net_dev = tfp.read()
tfp.close()
log.write("proc_net_dev:\n")
log.write(proc_net_dev)
log.write('\n')
log.write('\n--------------------------')
#if (iface == 'ppp0' or iface == 'ttyUSB0') and status == 'down':
if (iface != 'lo') and status == 'down':
#s = execute('iptables -L -v')
#rules = s.splitlines()
rx,tx = 0,0
rxdrop, txdrop = 0,0
#print 'rx=' + str(rx) + ' tx=' + str(tx)
#print 'rxdrop=' + str(rxdrop) + ' txdrop=' + str(txdrop)
#execute("iptables --zero")
header=''
lines=[]
if not os.path.exists(mypath + 'usage.csv'):
#create header
header = 'date,rx,tx,rx-dropped,tx-dropped,rx-tot,tx-tot\n'
f = open(mypath + 'usage.csv','a')
if len(header) > 0:
lines.append(header)
lines.append(str(datetime.datetime.now()).split('.')[0] + ',' + str(rx) + ',' + str(tx) + ',' + str(rxdrop) + ',' + str(txdrop) + ',' + str(rx+rxdrop) + ',' + str(tx+txdrop) + '\n')
#rx = execute('cat /sys/class/net/ppp0/statistics/rx_bytes')
#tx = execute('cat /sys/class/net/ppp0/statistics/tx_bytes')
#strdate=str(datetime.datetime.now())
#line = strdate + ',' + rx + ',' + tx + '\n'
f.writelines(lines)
f.close()
log.close()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment