查看linux网络流量小程序: netiostat

本文提供了一个Python脚本,用于实时监控网络接口eth0的流量输入输出情况,并计算每秒的平均速率。通过定时读取网络统计数据并计算差值,能够直观展示网络的流入和流出速度。

#!/usr/bin/python #coding=utf-8 #file : netiostat #author : flynetcn from __future__ import division import sys import os import time import signal netcmd = '/sbin/ifconfig eth0 | grep bytes' def getnetio(line): s1 = line.find('RX bytes:')+9 e1 = line.find(' ', s1) neti = line[s1:e1] s2 = line.find('TX bytes:')+9 e2 = line.find(' ', s2) neto = line[s2:e2] return (int(neti), int(neto)) def int_handler(signum, frame): print "" sys.exit() signal.signal(signal.SIGINT, int_handler) line = os.popen(netcmd).readline().strip() netio = getnetio(line) neti_start = netio[0] neto_start = netio[1] time_start = time.time() count = 60 while (count > 0): count -= 1 time.sleep(1); info = [] line = os.popen(netcmd).readline().strip() netio = getnetio(line) info.append("网络流入总量:%.4fm, 网络流出总量:%.4fm" % (netio[0]/1024/1024, netio[1]/1024/1024)) time_curr = time.time() neti_total = netio[0]-neti_start neto_total = netio[1]-neto_start sec_total = time_curr-time_start neti_start = netio[0] neto_start = netio[1] time_start = time_curr info.append("当前网络流入速度:%.4fk/s" % (neti_total/sec_total/1024)) info.append("当前网络流出速度:%.4fk/s" % (neto_total/sec_total/1024)) show = ", ".join(info) sys.stdout.write(show+"/r") sys.stdout.flush() print ""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值