python如何查看系统网络流量的信息

yipeiwu_com6年前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()函数获取流量信息,接下来都是一些数据处理的过程。

总结

以上就是这篇文章的全部内容了,希望对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。

相关文章

用Eclipse写python程序

用Eclipse写python程序

在上一篇文章里已经写过如何安装python和在eclipse中配置python插件,这篇就不多说了,开始入门。 1.先新建一个python工程,File-->New-->Ot...

对Python生成汉字字库文字,以及转换为文字图片的实例详解

对Python生成汉字字库文字,以及转换为文字图片的实例详解

笔者小白在收集印刷体汉字的深度学习训练集的时候,一开始就遇到的了一个十分棘手的问题,就是如何获取神经网络的训练集数据。通过上网搜素,笔者没有找到可用的现成的可下载的汉字的训练集,于是笔者...

Python3使用PyQt5制作简单的画板/手写板实例

Python3使用PyQt5制作简单的画板/手写板实例

1.前言 版本:Python3.6.1 + PyQt5 写一个程序的时候需要用到画板/手写板,只需要最简单的那种。原以为网上到处都是,结果找了好几天,都没有找到想要的结果。 网上的要么是...

Python中的函数作用域

在python中,一个函数就是一个作用域 name = 'xiaoyafei' def change_name(): name = '肖亚飞' print('在change_...

python 获取当天凌晨零点的时间戳方法

最近写python,遇到了一个问题,需要获取当日凌晨零点的时间戳,网上实在没有找到,自己手写了一个,有点挫 # -*- coding:utf-8 -*- import time...