Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 监控Linux流量Python版

Python版监控Linux流量,直接上代码,使用OptionParser来传入参数#coding:utf-8
#-------------
#Author:Hu
#Data:20150520
#-------------from __future__ import division
import re
import time
from optparse import OptionParser
def getbandwidth(eth="eth0",intevel=1):
    a=open("/proc/net/dev")
    data=a.read()
    patten=eth + ".*"
    if  not re.search(patten,data):
        print "The ETHname not have"
        exit(1)
    Rev_old=re.search(patten,data).group().replace(":"," ").split()[1]
    Send_old=re.search(patten,data).group().replace(":"," ").split()[9]
    a.close()    while True:
        #print intevel
        time.sleep(int(intevel))
        a=open("/proc/net/dev")
        data=a.read()
        Rev=re.search(patten,data).group().replace(":"," ").split()[1]
        Send=re.search(patten,data).group().replace(":"," ").split()[9]
        diff_Rev=int(Rev)-int(Rev_old)
        diff_Sen=int(Send)-int(Send_old)
        diff_M=diff_Rev*8/1024/1024/int(intevel)
        diff_S=diff_Sen*8/1024/1024/int(intevel)
        print time.strftime("%Y%m%d %H:%M:%S") + " The Recevie is  %6.2f Mbps(byte is %d)" % (diff_M,diff_Rev) + " The Send is  %6.2f Mbps(byte is %d)" % (diff_S,diff_Sen)
        Rev_old=Rev
        Send_old=Send
        a.close()
if __name__=="__main__":
   
    import sys
    usage="""%prog [-i ethname] [-t interveltime]
         Example:%prog -i eth0 -t 1"""
    parser=OptionParser(usage=usage,version="2.0_20150602")    parser.add_option("-i","--interface",dest="interface",default="eth0",help="Wann to interface")
    parser.add_option("-t","--time",dest="intevel",type="int",default="1",help="The intevel time")
    (options,args)=parser.parse_args()
    print "The interafce is %s and the intevel time is %d" % (options.interface,options.intevel)
    getbandwidth(options.interface,options.intevel)使用方法:
"""%prog [-i ethname] [-t interveltime]
         Example:%prog -i eth0 -t 1"""
默认是eth0 ,时间间隔是1下面关于Python的文章您也可能喜欢,不妨看看:Linux下Python的安装以及注意事项  http://www.linuxidc.com/Linux/2015-11/124861.htmUbuntu 14.04 下安装使用Python rq模块  http://www.linuxidc.com/Linux/2015-08/122441.htm无需操作系统直接运行 Python 代码  http://www.linuxidc.com/Linux/2015-05/117357.htmCentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里 本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-11/125152.htm