简体   繁体   中英

run vnstat from a python script

When running

vnstat -i [interface] --oneline

the selected interface's bandwidth usage is printed.

1;eth0;10/11/11;1.45 MiB;801 KiB;2.23 MiB;0.59 kbit/s;Oct '11;3.93 MiB;2.06 MiB;6.00 MiB;0.05 kbit/s;3.93 MiB;2.06 MiB;6.00 MiB

But to print all bandwidth usages from all interfaces, I need to run the following to get all the interfaces' name

vnstat --iflist

Then iterate through the result to store a usage result in a list

for item in result.split():
    # usage = run command 'vnstat --oneline -i [interface]
    # usageList.append(usage)
print ''.join(usageList)

The above script works but is running slow if there are many interfaces. How to optimize?

  1. Note that tons of awesome network stats are available in /proc/net/* -- very fast

  2. If you really want vnstat (which looks neat!), here's some code that scans each network interface in parallel.

    import multiprocessing, subprocess, time

    def check_net(iface): return ( iface, subprocess.check_output( ['vnstat','--oneline','-i',iface] ), )

    ifaces = subprocess.check_output( ['vnstat', '--iflist'] ).split()[2:]

    try: while True: pool = multiprocessing.Pool(len(ifaces)) for iface,output in pool.imap_unordered(check_net, ifaces): print iface.upper(), if 'Error' in output: print '?' else: print output.rstrip() print time.sleep(10) except KeyboardInterrupt: pass

Output:

LXCBR0 1;lxcbr0;06/02/14;0 KiB;3 KiB;3 KiB;0.00 kbit/s;Jun '14;0 KiB;3 KiB;3 KiB;0.00 kbit/s;0 KiB;3 KiB;3 KiB
WLAN0 1;wlan0;06/02/14;7.77 MiB;401 KiB;8.17 MiB;1.11 kbit/s;Jun '14;7.77 MiB;401 KiB;8.17 MiB;0.46 kbit/s;7.77 MiB;401 KiB;8.17 MiB
ETH0  eth0: Not enough data available yet.
LO ?

ETH0  eth0: Not enough data available yet.
LXCBR0 1;lxcbr0;06/02/14;0 KiB;3 KiB;3 KiB;0.00 kbit/s;Jun '14;0 KiB;3 KiB;3 KiB;0.00 kbit/s;0 KiB;3 KiB;3 KiB
WLAN0 1;wlan0;06/02/14;7.77 MiB;401 KiB;8.17 MiB;1.11 kbit/s;Jun '14;7.77 MiB;401 KiB;8.17 MiB;0.46 kbit/s;7.77 MiB;401 KiB;8.17 MiB
LO ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM