Skip to content

python 获取当前网速

创建于: 2015-05-28

项目地址

http://git.oschina.net/chenyanclyz/curspeed

基本原理

在 Linux 上,可以用ifconfig命令查看到网络接口的信息,包括本次开机某个网络接口收发了多少字节的数据。

注意是字节 byte,不是比特 bite。

我们每隔一段时间,获取一次 ifconfig 命令的输出结果,得到收发总字节的差,就能算出当前的实时网速。

使用 python 的 os.popen()执行 shell 命令,并得到命令的执行结果。用 re.sub()匹配出收发的总字节。

代码示例

py
#coding:utf8
'''python3 code support python2
author's email: chenyan@feling.net
通过统计ifconfig命令的输出,计算当前网速
'''

import logging
logging.basicConfig(level=logging.INFO,
                format='%(message)s'
                )

import os, sys, time
import re

def get_total_tx_bytes(interface, isCN):
    grep = '发送字节' if isCN else '"TX bytes"'
    r = os.popen('ifconfig '+interface+' | grep '+grep).read()
    total_bytes = re.sub('(.+:)| \(.+','',r)
    return int(total_bytes)

def get_total_rx_bytes(interface, isCN):
    grep = '接收字节' if isCN else '"RX bytes"'
    r = os.popen('ifconfig '+interface+' | grep '+grep).read()
    total_bytes = re.sub(' \(.+','',r)
    total_bytes = re.sub('.+?:','',total_bytes)
    return int(total_bytes)


if __name__=='__main__':
    interface = sys.argv[1]
    get_total_bytes = get_total_tx_bytes if sys.argv[2]=='tx' else get_total_rx_bytes
    isCN = True if sys.argv[3]=='cn' else False
    freq = int(sys.argv[4])
    while True:
        last = get_total_bytes(interface, isCN)
        time.sleep(freq)
        increase = get_total_bytes(interface, isCN) - last
        logging.info(str(increase/freq/1000))

运行示例:
系统语言是中文,每隔 1 秒统计一次 eth0 接口的上传速度

python curspeed.py eth0 tx cn 1

iftop 命令

iftop 可以在终端查看流量信息

另: osx 系统用 brew 命令安装 iftop 后, 执行发现找不到命令. 可执行文件的链接在 /usr/local/sbin 路径下, 需要修改 PATH 变量的内容的话, 可以编辑 /etc/paths 文件

追评(2021-11-30)

示例代码已经不能直接用了, n年过去, ifconfig 命令的输出已经变了. 里面匹配字节数的正则表达式已经失效了...还是用iftop靠谱.