前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python网速监控

Python网速监控

作者头像
py3study
发布2020-01-03 11:28:28
2.1K0
发布2020-01-03 11:28:28
举报
文章被收录于专栏:python3

Python网速监控脚本

功能: 统计网卡接收和发送的总流量,计算每秒的网速
代码如下:
代码语言:javascript
复制
#!/bin/env python36
import sys
import threading
import time


# 单位换算
def unit_conversion(byte):
    byte = int(byte)
    if byte > 1000:
        res = byte / 1024
        if res < 1000:
            res = float('%.2f' % res)
            return str(res) + 'k'
        elif res < 1000 * 1024:
            res = res / 1024
            res = float('%.2f' % res)
            return str(res) + 'm'
        else:
            res = res / (1024 * 1024)
            res = float('%.2f' % res)
            return str(res) + 'g'


def get_net_data(netdev):
    with open('/proc/net/dev', 'r') as f:
        for line in f:
            if line.find(netdev) >= 0:
                receive = line.split(':')[1].split()[0]
                transmit = line.split(':')[1].split()[8]
                return float(receive), float(transmit)


def speed_monitor(netdev):
    while True:
        receive_old, transmit_old = get_net_data(netdev)
        time.sleep(1)
        receive, transmit = get_net_data(netdev)
        print('recevice' + unit_conversion(receive - receive_old) + '/s')
        print('transmit' + unit_conversion(transmit - transmit_old) + '/s')


if __name__ == "__main__":
    if sys.argv[1] == "t":
        receive, transmit = get_net_data(sys.argv[2])
        print(unit_conversion(receive))
        print(unit_conversion(transmit))
    elif sys.argv[1] == "s":
        threading.Thread(target=speed_monitor,args=(sys.argv[2],)).start()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python网速监控脚本
    • 功能: 统计网卡接收和发送的总流量,计算每秒的网速
      • 代码如下:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档