linux 统计网卡流量小脚本

#!/usr/bin/python
#
#       zhaoyun
#
#

import re,time,sys,string


file = "/proc/net/dev"

def get_eth(eth):
        ethx = []
        for i in eth.split(','):
                ethx.append(i)

        return ethx

def get_data(ethx):
        f    = open(file,"r").readlines()
        for i in f:
                r =  re.findall(r"%(ethx)s:.*." % vars(),i)
                if r:
                        a =  "".join(r).split()
                        input   =  a[0].split(':')[1:]
                        for input_value in input:
                                input = int(input_value)
                        output  =  int(a[8])
                        return input,output

def get_data_value(eth):
        data = []
        for ethx in eth:
                data1 = get_data(ethx)
                data.append(data1)
        return data


def count_value_input(data,n,l):
        count = 1
        for i in data:
                if count == n:
                        try:
                                for inp in i:
"1.py" 125L, 2227C written                                                                                                                           3,2-8         Top

        for i in range(1,len(dataa)+1):
                inp1 = count_value_input(dataa,i,i)
                inp2 = count_value_input(datab,i,i)
                print_(inp1,inp2,"input",i,eth)
                out1 = count_value_output(dataa,i,i)
                out2 = count_value_output(datab,i,i)
                print_(out1,out2,"output",i,eth)


def get_param(para,number):
        c = 0
        count = 0
        p = []
        try:
                for i in sys.argv:
                        if i == para:
                                p.append(sys.argv[c+1])
                                count+=1
                        c +=1
                        if count == int(number):
                                return string.join(p)

        except Exception:
                return i+' Parameter Error'

def help_():
        print '''
        python %s -T 1 -I eth0,eth1,lo  
        ''' %(sys.argv[0])


eth  = get_param("-I",1)
Time = get_param("-T",1)

if eth and Time:
        try:
                Time = int(Time)
        except Exception:
                print "Time error"
                sys.exit(2)
        start_(eth,Time)
else:
        help_()

 

 

 

使用方法:

#python 1.py -T 1 -I eth0,eth1
eth0    input   :18854
eth0    output  :1844
eth1    input   :836
eth1    output  :836

 

 

 

你可能感兴趣的:(shell,python,统计网卡流量)