python小脚本,linux下实时查看网卡流量与pps

可自定义刷新频率,最低为1秒,运行结束后进行结果汇总

#! /usr/bin/env python
#-*-coding:utf-8-*-
# from __future__ import division
# from ast import Raise
# from operator import invert
import time,sys,os
import signal,psutil
class Traffic:
    def __init__(self,name,interval):
        signal.signal(signal.SIGINT, self.signal_handler)
        self.bps_in_max = 0
        self.bps_out_max = 0
        self.bps_in_min = 999999999999
        self.bps_out_min = 999999999999
        self.bps_in_sum = 0
        self.bps_out_sum = 0
        self.pps_in_max = 0
        self.pps_out_max = 0
        self.pps_in_min = 999999999999
        self.pps_out_min = 999999999999
        self.pps_in_sum = 0
        self.pps_out_sum = 0
        self.count = 0
        self.name = name
        self.interval = int(interval)
        self.starttime = time.strftime('%Y-%m-%d %H:%M:%S')
    def init_ret(self):
        
        net_io_counters = psutil.net_io_counters(pernic=True)
        if self.name in net_io_counters:
            net_io = net_io_counters[self.name]
            bytes_sent = net_io.bytes_sent
            bytes_recv = net_io.bytes_recv
            packet_sent = net_io.packets_sent
            packet_recv = net_io.packets_recv
            return bytes_sent,bytes_recv,packet_sent,packet_recv
        else:
            print(f'{self.name}不存在')
    def run(self):
        bytes_sent,bytes_recv,packet_sent,packet_recv = self.init_ret()
        while True:
            # 获取每个网卡的流量信息
            time.sleep(self.interval)
            net_io_counters2 = psutil.net_io_counters(pernic=True)
            net_io2 = net_io_counters2[self.name]
            bytes_sent2 = net_io2.bytes_sent
            bytes_recv2 = net_io2.bytes_recv
            packet_sent2 = net_io2.packets_sent
            packet_recv2 = net_io2.packets_recv
            error = net_io2.errin+net_io2.errout
            drop = net_io2.dropin+net_io2.dropout
            send_traffic = round((bytes_sent2 - bytes_sent)*8/1024/1024/self.interval,2)
            recv_traffic = round((bytes_recv2 - bytes_recv)*8/1024/1024/self.interval,2)
            send_packet = (packet_sent2 -packet_sent)/self.interval
            recv_packet = (packet_recv2 - packet_recv)/self.interval
            bytes_sent,bytes_recv,packet_sent,packet_recv=bytes_sent2,bytes_recv2,packet_sent2,packet_recv2
            self.bps_in_max = max(recv_traffic,self.bps_in_max)
            self.bps_out_max = max(send_traffic,self.bps_out_max)
            self.bps_in_min = min(recv_traffic,self.bps_in_min)
            self.bps_out_min = min(send_traffic,self.bps_out_min)
            self.bps_in_sum += recv_traffic
            self.bps_out_sum += send_traffic
            self.pps_in_max = max(recv_packet,self.pps_in_max)
            self.pps_out_max = max(send_packet,self.pps_out_max)
            self.pps_in_min = min(recv_packet,self.pps_in_min)
            self.pps_out_min = min(send_packet,self.pps_out_min)
            self.pps_in_sum += recv_packet
            self.pps_out_sum += send_packet
            self.count+=1
            bps_in_show = f'incoming: {recv_traffic}Mbps'
            bps_out_show = f'outgoing: {send_traffic}Mbps'
            pps_in_show = f'incoming: {recv_packet}pps'
            pps_out_show = f'outgoing: {send_packet}pps'
            os.system('clear')
            print('----------------------'+self.name+' errors'+'--------------------------')
            print('errors:',error)
            print('drop:',drop)
            print('-----------'+self.name+' '+str(self.interval)+' second interval bps monitoring'+'-----------')
            print(bps_in_show)
            print(bps_out_show)
            print('-----------'+self.name+' '+str(self.interval)+' second interval pps monitoring'+'-----------')
            print(pps_in_show)
            print(pps_out_show)
    def signal_handler(self,*args, **kwargs):
        try:
            if self.count!=0:
                os.system('reset')
                print('---------------------------%s至%s----------------------------'%(self.starttime,time.strftime('%Y-%m-%d %H:%M:%S')))
                print('------------%s bps------------'%self.name)
                print('               min          max          avg')
                print('incoming    %sM        %sM        %sM'%(self.bps_in_min,self.bps_in_max,round(self.bps_in_sum/self.count,2)))
                print('outgoing    %sM        %sM        %sM'%(self.bps_out_min,self.bps_out_max,round(self.bps_out_sum/self.count,2)))
                print('------------%s pps------------'%self.name)
                print('               min          max          avg')
                print('incoming    %spps        %spps        %spps'%(self.pps_in_min,self.pps_in_max,round(self.pps_in_sum/self.count,2)))
                print('outgoing    %spps        %spps        %spps'%(self.pps_out_min,self.pps_out_max,round(self.pps_out_sum/self.count,2)))
        except:
            os._exit(0)
        os._exit(0)
if __name__ == '__main__':
    try:
        name = sys.argv[1]
        interval = int(sys.argv[2])
        if interval < 1:
            raise ValueError('interval must gt 1')
        obj = Traffic(name,interval)
        obj.run()
    except Exception as e:
        print(e)
        print('argv:')
        print('NetworkName,interval')
        print('example:')
        print(' ./networkpps  eth0 1')

Leave a Reply

Your email address will not be published. Required fields are marked *

X