首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → python如何查看系统网络流量信息例子分享

python如何查看系统网络流量信息例子分享

来源:维维整理 发布时间:2016-9-13 17:52:13 人气:

今天要给各位朋友带来关于python如何查看系统网络流量信息例子,有兴趣的朋友快来详细了解下吧。

前言

流量信息能够直接在/proc/net/dev中进行查看,笔者实现的程序使用命令:

python net.py interface

其中interface为网卡名称,使用什么网卡,电脑有哪一些网卡,可以使用

sudo ifconfig

进行查看。

Python实现的程序如下:

# coding:utf-8
import sys, time, os

'''
Inter-|  Receive                        | Transmit
 face |bytes  packets errs drop fifo frame compressed multicast|bytes  packets errs drop fifo colls carrier compressed
  lo:  28169   364  0  0  0   0     0     0  28169   364  0  0  0   0    0     0
 wlan1: 7432984  6018  0  0  0   0     0     0  681381  6115  0  0  0   0    0     0
vmnet1:    0    0  0  0  0   0     0     0    0   56  0  0  0   0    0     0
vmnet8:    0    0  0  0  0   0     0     0    0   55  0  0  0   0    0     0
 eth0:    0    0  0  0  0   0     0     0    0    0  0  0  0   0    0     0

'''
_unit_=['B','KB','MB','GB','TB']

def get_net_data(interface):
  for line in open('/proc/net/dev', 'r'):
    if line.split(':')[0].find(interface)>=0:
      return map(int, line.split(':')[1].split())

def convert_bytes_to_string(b):
  cnt = 0
  while b >= 1024.0:
    b = float(b) / 1024.0
    cnt += 1
  return '%.2f%s'%(b,_unit_[cnt])

if __name__ == '__main__':
  interface = sys.argv[1]
  while True:
    net_data = get_net_data(interface)
    receive_data_bytes = net_data[0]
    transmit_data_bytes = net_data[8]
    os.system('clear')
    print 'Interface:%s  -> Receive Data: %s  Transmit Data: %s'%(interface, convert_bytes_to_string(receive_data_bytes), convert_bytes_to_string(transmit_data_bytes))
    time.sleep(1)

程序入口从if name=='main'处开始,首先通过参数获取interface,接着调用get_net_data()函数获取流量信息,接下来都是一些数据处理的过程。

相关下载
栏目导航
本类热门阅览