首页 > 编程语言 > 详细

网卡流量监控脚本 ( Python )

时间:2016-06-30 17:59:17      阅读:251      评论:0      收藏:0      [点我收藏+]
#!/usr/bin/env python
# coding: utf-8
# author: Xiao Guaishou

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:
        net_in.setdefault(key, (now_recv.get(key) - old_recv.get(key)) / 1024)
        net_out.setdefault(key, (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:
             print(%s\nInput:\t %-5sKB/s\nOutput:\t %-5sKB/s\n % (key, net_in.get(key), net_out.get(key)))
    except KeyboardInterrupt:
        exit()

# End

网卡流量监控脚本 ( Python )

原文:http://www.cnblogs.com/wangxiaoqiangs/p/5630395.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!