zoukankan      html  css  js  c++  java
  • psutil模块获取网卡流量

    使用python监控系统时,获取网卡流量是比较难搞的,网上找了一个比较好的脚本,分享一下!

    psutil模块是一个跨平台的获取进程和系统应用情况(CPU,内存,磁盘,网络,传感器)的库。该模块用于系统监控、限制进程资源和运行进程的管理等方面

    安装模块psutil

    pip install psutil

    亲测Linux和Windows使用正常

    net_traffic.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    try:
        import psutil
    except ImportError:
        print('Error: psutil module not found!')
        exit()
    
    
    def get_key():
    
        key_info = psutil.net_io_counters(pernic=True).keys()
    
        recv = {}
        sent = {}
    
        for key in key_info:
            recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv)
            sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent)
    
        return key_info, recv, sent
    
    
    def get_rate(func):
    
        import time
    
        key_info, old_recv, old_sent = func()
    
        time.sleep(1)
    
        key_info, now_recv, now_sent = func()
    
        net_in = {}
        net_out = {}
    
        for key in key_info:
            # float('%.2f' % a)
            net_in.setdefault(key, float('%.2f' %((now_recv.get(key) - old_recv.get(key)) / 1024)))
            net_out.setdefault(key, float('%.2f' %((now_sent.get(key) - old_sent.get(key)) / 1024)))
    
        return key_info, net_in, net_out
    
    
    while 1:
        try:
             key_info, net_in, net_out = get_rate(get_key)
    
             for key in key_info:
                 # lo 是linux的本机回环网卡,以太网是我win10系统的网卡名
                 if key != 'lo' or key == '以太网':
                    print('%s
    Input:	 %-5sKB/s
    Output:	 %-5sKB/s
    ' % (key, net_in.get(key), net_out.get(key)))
        except KeyboardInterrupt:
            exit()

    注意:以太网是我win10网卡名,可自行更改

    数字显示,改成保留小数点2位,使用float

    运行脚本,使用迅雷下载一步高清电影,效果如下:

    动画1.gif

    将代码拷贝到Linux服务器,运行一下。

    下载一个软件包,效果如下:

    blob.png

  • 相关阅读:
    BZOJ2705: [SDOI2012]Longge的问题 欧拉函数
    BZOJ3884: 上帝与集合的正确用法 拓展欧拉定理
    BZOJ1296: [SCOI2009]粉刷匠 DP
    BZOJ5293: [Bjoi2018]求和 树上差分
    BZOJ1398: Vijos1382寻找主人 Necklace 字符串最小表示法
    BZOJ5189: [Usaco2018 Jan]Cow at Large 贪心+LCA
    BZOJ2654: tree 二分答案+最小生成树
    BZOJ1304: [CQOI2009]叶子的染色 树形dp
    BZOJ1632: [Usaco2007 Feb]Lilypad Pond SPFA+最短路计数
    BZOJ1726: [Usaco2006 Nov]Roadblocks第二短路 K短路
  • 原文地址:https://www.cnblogs.com/liqing1009/p/12604558.html
Copyright © 2011-2022 走看看