您的位置:首页 > 运维架构 > Linux

python:查看linux网卡流量

2013-09-20 16:29 337 查看
此脚本可列出一定时间的流量及平均流量。时间可自己设置。
#!/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等等。比较懒,没有做参数判断。也就是参数里输入任何字符串都不会报错,当然脚本运行获取的结果也就不会正确。

本文出自 “哲就是我” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: