linux网速监控脚本

Zss 发表于:

嵌入式的linux系统实在没找到个实时的网速查看的脚本或者工具,所以通过每秒的流量计算做一个实时的流量监控工具,centos没法用,ifconfig出来的信息和公司设备显示不一样,所以抓取数据错了,只需要改一下抓取的正确数据就可以了

centos改

if ‘bytes’ in i.strip():
info = re.findall(r’\s(.*)\s\((.*)\)’,i.strip())[0]

# coding:utf8
from subprocess import PIPE, Popen
import re, time, sys


def network_flow(face):
    # return [(rx_data,rx_all_data),(tx_data,tx_all_data)]
    data = []
    cmd = 'ifconfig %s | grep bytes' % face
    result = Popen(cmd, shell=True, stdout=PIPE)
    for i in result.stdout.read().split('  '):
        if '' != i.strip():
            info = re.findall(r':(.*)(?:\s{1,5}\()(.*)\)', i.strip())[0]
            data.append(info)
    return data


def format(number):
    if len(number) < 4:
        return ('%dB/s' % int(number), '%dBps' % (int(number) * 8))
    elif len(number) < 7:
        return ('%dKB/s' % (int(number) / 1000), '%dKBps' % (int(number) / 1000 * 8))
    else:
        return ('%dMB/s' % (int(number) / 1000000), '%dMBps' % (int(number) / 1000000 * 8))


def main():
    start = network_flow(face)
    time.sleep(0.996)
    end = network_flow(face)
    rx_info = (int(end[0][0]) - int(start[0][0]), end[0][1])
    tx_info = (int(end[1][0]) - int(start[1][0]), end[1][1])
    total_info = (rx_info[0] + tx_info[0])

    print '%s' % (time.ctime())
    print 'RX_Speed : %s  %s     RX_Flow : %s' % (format(str(rx_info[0]))[0], format(str(rx_info[0]))[1], rx_info[1])
    print 'TX_Speed : %s  %s     TX_Flow : %s' % (format(str(tx_info[0]))[0], format(str(tx_info[0]))[1], tx_info[1])
    print 'Total_Speed : %s %s\n' % (format(str(total_info))[0], format(str(total_info))[1])


if __name__ == '__main__':
    try:
        face = sys.argv[1]
        while 1:
            main()
    except:
        print '     Need a interface name'
        print 'E.g: python network_speed.py eth0'