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

总结

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

相关文章

Python中线程的MQ消息队列实现以及消息队列的优点解析

“消息队列”是在消息的传输过程中保存消息的容器。消息队列管理器在将消息从它的源中继到它的目标时充当中间人。队列的主要目的是提供路由并保证消息的传递;如果发送消息时接收者不可用,消息队列会...

python程序变成软件的实操方法

python程序变成软件的实操方法

本人新学python,发现python程序转成软件好麻烦,为了方便大家,同时自己整理下资源,发布以下教程哦。 下载 “pywin32”软件,选择最新的build文件夹,支持新版本的pyt...

浅谈django的render函数的参数问题

hello.html 文件代码如下: HelloWorld/templates/hello.html 文件代码: <h1>{{ hello }}</h1>...

python逐行读取文件内容的三种方法

方法一:复制代码 代码如下:f = open("foo.txt")          ...

python利用7z批量解压rar的实现

一开始我使用了rarfile这个库,奈何对于含有密码的压缩包支持不好,在linux上不抛出异常;之后有又尝试了unrar。。比rarfile还费劲。。 所以用了调用系统命令的方法,用7z...