发布时间:2019-09-17 07:43:02编辑:auto阅读(1616)
此脚本可列出一定时间的流量及平均流量。时间可自己设置。
#!/usr/bin/env python import time,sys def all_flow(INTERFACE): f = open('/proc/net/dev') flow_info=f.readlines() in_flow=[] out_flow=[] for eth_dev in flow_info: if INTERFACE in eth_dev: in_flow.append(int(eth_dev.split(':')[1].split()[0])) out_flow.append(int(eth_dev.split(':')[1].split()[9])) f.close() return in_flow,out_flow def format_flow(flow): flow_n = float(flow) if flow_n > 1000000: return '%.3f MB' % (flow_n/1024/1024) else: return '%.3f KB' % (flow_n/1024) if __name__=='__main__': if len(sys.argv) > 1: INTERFACE = sys.argv[1] else: INTERFACE = 'eth' in_flows = {} out_flows = {} all_flows0 = all_flow(INTERFACE) count = 0 while count < 5: time.sleep(1) all_flows1=all_flow(INTERFACE) for x in range(len(all_flows0[0])): if len(sys.argv) >1: curr_eth = INTERFACE else: curr_eth = 'eth%s' % x if len(in_flows) == x: in_flows[curr_eth]= [] out_flows[curr_eth]=[] print curr_eth+" in:"+ format_flow(all_flows1[0][x]-all_flows0[0][x])+" out:"+\ format_flow(all_flows1[1][x]-all_flows0[1][x]) in_flows[curr_eth].append(all_flows1[0][x]-all_flows0[0][x]) out_flows[curr_eth].append(all_flows1[1][x]-all_flows0[1][x]) all_flows0 = all_flows1 count=count+1 for key in in_flows: sum_a=0 in_flow='' for i in in_flows[key]: sum_a = sum_a+i in_flow = in_flow + format_flow(i) + ' ' #print key + ' flow_in is: %s'% in_flow print key +" average of flow_in is: %s" % format_flow(sum_a/count) for key in out_flows: sum_a=0 out_flow='' for i in out_flows[key]: sum_a = sum_a+i out_flow = out_flow + format_flow(i) + ' ' #print key + ' flow_out is: %s'% out_flow print key +" average of flow_out is: %s" % format_flow(sum_a/count)
默认为列出除lo以外的所有网卡的流量。也可在运行时加入网卡名作为参数如:eth0 或eth1等等。比较懒,没有做参数判断。也就是参数里输入任何字符串都不会报错,当然脚本运行获取的结果也就不会正确。
上一篇: Python实现atm机的功能
下一篇: HBuilder集成Python开发环境
47841
46390
37281
34733
29312
25973
24913
19950
19544
18030
5791°
6413°
5927°
5961°
7064°
5911°
5942°
6437°
6404°
7778°