監控網卡流量python代碼

y0657bys 8年前發布 | 3K 次閱讀 Python

[Python]代碼    

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()
 本文由用戶 y0657bys 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!