简体   繁体   English

从python脚本运行vnstat

[英]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 请注意, / proc / net / *中提供了大量令人敬畏的网络统计信息-非常快

  2. If you really want vnstat (which looks neat!), here's some code that scans each network interface in parallel. 如果您真的想要vnstat (看起来很漂亮!),下面是一些可以并行扫描每个网络接口的代码。

    import multiprocessing, subprocess, time 导入多处理,子流程,时间

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

    ifaces = subprocess.check_output( ['vnstat', '--iflist'] ).split()[2:] 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 '?' 试试:while True:pool = multiprocessing.Pool(len(ifaces))for iface,在pool.imap_unordered(check_net,ifaces)中输出:打印iface.upper(),如果输出中有'Error':print'?' else: print output.rstrip() print time.sleep(10) except KeyboardInterrupt: pass else:打印output.rstrip()打印time.sleep(10),KeyboardInterrupt除外:通过

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 ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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