Created
May 25, 2012 09:58
-
-
Save rswofxd/2787073 to your computer and use it in GitHub Desktop.
Python:网卡流量统计实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding:utf-8 | |
import re,time | |
def get_net_info(): | |
flow1 = open('/proc/net/dev') | |
lines = flow1.read() | |
flow1.close() | |
e = re.compile('(eth.)') | |
r_re = re.compile('eth..(.*?\s)') | |
r_tr = re.compile(".*eth.*") | |
match_re = r_re.findall(lines) | |
match_tr = r_tr.findall(lines) | |
eth = e.findall(lines) | |
return (eth,lines,match_re,match_tr) | |
def net_flow(): | |
net_re_c={} | |
net_tr_c={} | |
net_tr_a=[] | |
for i in get_net_info()[3]: | |
net_tr_a.append(i.split()[8]) | |
net_tr_a=dict(zip(get_net_info()[0],net_tr_a)) | |
net_re_a = dict(zip(get_net_info()[0],get_net_info()[2])) | |
print "{eth0:(transmit,receive)" | |
while True: | |
time.sleep(1) | |
net_re_b = dict(zip(get_net_info()[0],get_net_info()[2])) | |
net_tr_b = [] | |
for i in get_net_info()[3]: | |
net_tr_b.append(i.split()[8]) | |
net_tr_b=dict(zip(get_net_info()[0],net_tr_b)) | |
for i in net_re_b: | |
net_re_c[i] = int((float(net_re_b[i])-float(net_re_a[i]))/1024) | |
for i in net_tr_b: | |
net_tr_c[i]=int((float(net_tr_b[i])-float(net_tr_a[i]))/1024) | |
net_re_a = net_re_b | |
net_tr_a = net_tr_b | |
net_flow={} | |
for a in net_re_c: | |
net_flow[a]=(net_tr_c[a],net_re_c[a]) | |
print net_flow | |
if __name__ == "__main__": | |
net_flow() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment